├── .editorconfig ├── .gitignore ├── CHANGELOG.md ├── COPYING ├── LICENSE ├── README.md ├── keymaps └── php-integrator-refactoring.cson ├── lib ├── AbstractProvider.coffee ├── ConstructorGenerationProvider.coffee ├── ConstructorGenerationProvider │ └── View.coffee ├── DocblockProvider.coffee ├── ExtractMethodProvider.coffee ├── ExtractMethodProvider │ ├── Builder.coffee │ ├── ParameterParser.coffee │ └── View.coffee ├── GetterSetterProvider.coffee ├── GetterSetterProvider │ └── View.coffee ├── IntroducePropertyProvider.coffee ├── Main.coffee ├── OverrideMethodProvider.coffee ├── OverrideMethodProvider │ └── View.coffee ├── StubAbstractMethodProvider.coffee ├── StubAbstractMethodProvider │ └── View.coffee ├── StubInterfaceMethodProvider.coffee ├── StubInterfaceMethodProvider │ └── View.coffee └── Utility │ ├── DocblockBuilder.coffee │ ├── FunctionBuilder.coffee │ ├── MultiSelectionView.coffee │ └── TypeHelper.coffee ├── package.json └── styles └── main.less /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | indent_style = space 8 | indent_size = 4 9 | charset = utf-8 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | npm-debug.log 3 | node_modules 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.4.1 2 | * [Fix generating methods for properties without any `@var` tag not working](https://github.com/php-integrator/atom-refactoring/issues/51) 3 | 4 | ## 1.4.0 (base 3.0.0) 5 | * [Improve package activation time](https://github.com/php-integrator/atom-refactoring/issues/46) 6 | * [PHP 7.1's `iterable` and `void` scalar types are now supported](https://github.com/php-integrator/atom-refactoring/issues/48) 7 | * [Explicitly nullable types in PHP 7.1 will now be mimicked in getter and setter generation, constructor generation, ...](https://github.com/php-integrator/atom-refactoring/issues/45) 8 | * [Extract method now supports PHP 7.0 and PHP 7.1 scalar types for parameters](https://github.com/php-integrator/atom-refactoring/issues/20) 9 | * [Extract method now supports PHP 7.0 return types](https://github.com/php-integrator/atom-refactoring/issues/20) 10 | * [Unimplemented interface methods will no longer show up when overriding methods (they already show up in the `Stub Unimplemented Interface Method(s)` menu)](https://github.com/php-integrator/atom-refactoring/issues/49) 11 | * [Unoveridden abstract methods will no longer show up when overriding methods (they already show up in the `Stub Unimplemented Abstract Method(s)` menu)](https://github.com/php-integrator/atom-refactoring/issues/49) 12 | * [Fix reference parameters missing the leading '&' in generated docblocks](https://github.com/php-integrator/atom-refactoring/issues/37) 13 | * [Don't try to return the value of the parent method call when overriding a constructor](https://github.com/php-integrator/atom-refactoring/issues/39) 14 | * Due to changes in the core, overriding or implementing methods with explicit nullability from PHP 7.1 (the question mark) should now work properly 15 | * Fix `public` still being used as access modifier even though the default was set to `protected` when extracting methods 16 | * `Generate Constructor` will now always remain available and never disappear from the action list 17 | * Previously, it disappeared when a constructor was added, but only if it was added in the current class, i.e. not an ancestor. 18 | * This was troublesome when you wanted to quickly generate a new constructor after removing the existing one, as you always had to pause a moment for indexing to catch up on the fact that it was removed. 19 | 20 | ## 1.3.1 21 | * Fix deprecations. 22 | 23 | ## 1.3.0 (base 2.0.0) 24 | * The extract method preview panel is now syntax highlighted. 25 | * Fix docblocks for constructors sometimes getting a `@return self`. 26 | * Fix the button bar in dialogs falling outside the bottom of the dialog. 27 | * The intentions package will now be installed automatically, if necessary. 28 | * Fix not being able to generate a constructor in classes that have no properties. 29 | * The default access modifier when extracting methods is now `protected` since you seldom want to expose new methods in a class' API whilst extracting methods. 30 | * When generating method bodies, your preferred line length will now be taken into account. This means that parameter lists will be automatically wrapped over multiple lines if they are too long. 31 | * The `Enable PHP 7 Support` checkboxes have been removed. Whether or not PHP 7 is to be used is now determined automatically from your project's PHP version. No more having to manually click the checkbox every time. 32 | * Generated setters will no longer return `self` in PHP 7. The docblock type will still indicate `static`, but making the return type hint `self` will prevent them from being overridden to return a child class instance. 33 | * When overriding methods that have a return value, code will now be generated that catches and returns the return value from the automatically generated `parent::` call. 34 | * This is useful as usually one adds additional logic but still returns or further manipulates the parent value. 35 | 36 | ## 1.1.1 37 | * Rename the package and repository. 38 | 39 | ## 1.1.0 40 | * Added the ability to introduce new class properties. 41 | * Updated atom-space-pen-views to 2.2.0. This causes modal dialogs not to disappear when Atom is unfocused. 42 | 43 | ## 1.0.0 (base 1.0.0) 44 | * Rewrote the code to support multiple types. 45 | * Added the ability to generate constructors. 46 | * Added the ability to override existing methods. 47 | * Added the ability to generate unimplemented abstract methods. 48 | * Added the ability to generate unimplemented interface methods. 49 | * The getter and setter generator will now maintain the indentation level of the cursor. 50 | * Fixed parameters types and the return type not always being localized when extracting a method. 51 | * Fixed the extract method preview wrapping code to the next line instead of providing a horizontal scrollbar. 52 | * Lists are no longer alphabetically sorted. The ordering they are returned in is now maintained, which feels more fluent as it is the same order the items are defined in. 53 | 54 | * The docblock generator learned how to properly generate docblocks for variadic parameters: 55 | 56 | ```php 57 | // -- Before 58 | /** 59 | * @param Foo $foo 60 | */ 61 | protected function (Foo ...$foo) {} 62 | 63 | // -- After 64 | /** 65 | * @param Foo[] ...$foo 66 | */ 67 | protected function (Foo ...$foo) {} 68 | ``` 69 | 70 | ## 0.5.0 (base 0.9.0) 71 | * Tweaked some defaults. 72 | * Add basic support for generating docblocks. 73 | * Setters will now generate a docblock with `@return static` instead of `@return $this`. The latter is not mentioned by the draft PSR-5 anymore. 74 | * The extract method command will now suggest class names relative to the use statements when type hinting (rather than always suggest an FQCN). 75 | * *Important*: The [intentions](https://github.com/steelbrain/intentions) package is now required. 76 | * You can now use intentions (bound to alt-enter by default) to perform various refactoring actions in certain contexts, for example: 77 | * Press alt-enter when code is selected to extract a method. 78 | * Press alt-enter inside a classlike to generate getters and setters. 79 | * Press alt-enter with the cursor on a method name to generate its docblock. 80 | 81 | ## 0.4.2 (base 0.8.0) 82 | * Update to use the most recent version of the base service. 83 | 84 | ## 0.4.1 85 | * Don't throw an error when no current class name is found. 86 | * Perform more operations asynchronously whilst fetching properties for generating getters and setters, improving responsiveness. 87 | 88 | ## 0.4.0 (base 0.7.0) 89 | * Fixed promise rejections not being handled. 90 | * Added support for extracting methods based on CWDN's original [php-extract-method](https://github.com/CWDN/php-extract-method) package (thanks to @CWDN). 91 | * When generating setters, type hints will no longer be generated if multiple types are possible (with the exception of a type-hintable type and `null`, see also below). 92 | * When generating setters for type-hintable types that are also nullable, such as `Foo|null` or even `string|null` in PHP 7, an `= null` will now be added to the setter's parameter. 93 | 94 | ## 0.3.0 (base 0.6.0) 95 | * Added support for generating PHP 7 getters and setters. 96 | * Added the keyboard shortcut `shift + return` for confirming dialogs (cfr. git-plus). 97 | 98 | ## 0.2.0 (base 0.5.0) 99 | * Initial release. 100 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | © 2015 Tom Gerrits 2 | 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | 13 | You should have received a copy of the GNU General Public License 14 | along with this program. If not, see . 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # php-integrator/atom-refactoring 2 | ## Legacy 3 | This is a legacy version that required PHP >= 7.1. Since 3.6, its functionality is included in the [base package](https://github.com/php-integrator/atom-base) and installing it separately is no longer necessary. 4 | 5 | ## About 6 | This package provides refactoring capabilities for your PHP source code using [PHP Integrator](https://github.com/php-integrator/atom-base). 7 | 8 | **Note that the [php-integrator-base](https://github.com/php-integrator/atom-base) package is required and needs to be set up correctly for this package to function correctly.** 9 | 10 | **Note that the [intentions](https://github.com/steelbrain/intentions) package is also required. Intentions trigger using the `alt-enter` key by default.** 11 | 12 | What is included? 13 | * Method extraction. 14 | * Method overriding. 15 | * Constructor generation. 16 | * Getter and setter generation. 17 | * Unimplemented abstract method generation. 18 | * Unimplemented interface method generation. 19 | * Docblock generation (press `alt-enter` whilst on a functionlike, classlike or constant). 20 | 21 | ![GPLv3 Logo](http://gplv3.fsf.org/gplv3-127x51.png) 22 | -------------------------------------------------------------------------------- /keymaps/php-integrator-refactoring.cson: -------------------------------------------------------------------------------- 1 | # Keybindings require three things to be fully defined: A selector that is 2 | # matched against the focused element, the keystroke and the command to 3 | # execute. 4 | # 5 | # Below is a basic keybinding which registers on all platforms by applying to 6 | # the root workspace element. 7 | 8 | # For more detailed documentation see 9 | # https://atom.io/docs/latest/behind-atom-keymaps-in-depth 10 | 'atom-text-editor': 11 | 'alt-m': 'php-integrator-refactoring:extract-method' 12 | -------------------------------------------------------------------------------- /lib/AbstractProvider.coffee: -------------------------------------------------------------------------------- 1 | module.exports = 2 | 3 | ##* 4 | # Base class for providers. 5 | ## 6 | class AbstractProvider 7 | ###* 8 | * The service (that can be used to query the source code and contains utility methods). 9 | ### 10 | service: null 11 | 12 | ###* 13 | * Service to insert snippets into the editor. 14 | ### 15 | snippetManager: null 16 | 17 | ###* 18 | * Constructor. 19 | ### 20 | constructor: () -> 21 | 22 | ###* 23 | * Initializes this provider. 24 | * 25 | * @param {mixed} service 26 | ### 27 | activate: (@service) -> 28 | dependentPackage = 'language-php' 29 | 30 | # It could be that the dependent package is already active, in that case we can continue immediately. If not, 31 | # we'll need to wait for the listener to be invoked 32 | if atom.packages.isPackageActive(dependentPackage) 33 | @doActualInitialization() 34 | 35 | atom.packages.onDidActivatePackage (packageData) => 36 | return if packageData.name != dependentPackage 37 | 38 | @doActualInitialization() 39 | 40 | atom.packages.onDidDeactivatePackage (packageData) => 41 | return if packageData.name != dependentPackage 42 | 43 | @deactivate() 44 | 45 | ###* 46 | * Does the actual initialization. 47 | ### 48 | doActualInitialization: () -> 49 | atom.workspace.observeTextEditors (editor) => 50 | if /text.html.php$/.test(editor.getGrammar().scopeName) 51 | @registerEvents(editor) 52 | 53 | # When you go back to only have one pane the events are lost, so need to re-register. 54 | atom.workspace.onDidDestroyPane (pane) => 55 | panes = atom.workspace.getPanes() 56 | 57 | if panes.length == 1 58 | @registerEventsForPane(panes[0]) 59 | 60 | # Having to re-register events as when a new pane is created the old panes lose the events. 61 | atom.workspace.onDidAddPane (observedPane) => 62 | panes = atom.workspace.getPanes() 63 | 64 | for pane in panes 65 | if pane != observedPane 66 | @registerEventsForPane(pane) 67 | 68 | ###* 69 | * Registers the necessary event handlers for the editors in the specified pane. 70 | * 71 | * @param {Pane} pane 72 | ### 73 | registerEventsForPane: (pane) -> 74 | for paneItem in pane.items 75 | if atom.workspace.isTextEditor(paneItem) 76 | if /text.html.php$/.test(paneItem.getGrammar().scopeName) 77 | @registerEvents(paneItem) 78 | 79 | ###* 80 | * Deactives the provider. 81 | ### 82 | deactivate: () -> 83 | 84 | ###* 85 | * Retrieves intention providers (by default, the intentions menu shows when the user presses alt-enter). 86 | * 87 | * This method should be overwritten by subclasses. 88 | * 89 | * @return {array} 90 | ### 91 | getIntentionProviders: () -> 92 | return [] 93 | 94 | ###* 95 | * Registers the necessary event handlers. 96 | * 97 | * @param {TextEditor} editor TextEditor to register events to. 98 | ### 99 | registerEvents: (editor) -> 100 | 101 | ###* 102 | * Sets the snippet manager 103 | * 104 | * @param {Object} @snippetManager 105 | ### 106 | setSnippetManager: (@snippetManager) -> 107 | 108 | ###* 109 | * @return {Number|null} 110 | ### 111 | getCurrentProjectPhpVersion: () -> 112 | projectSettings = @service.getCurrentProjectSettings() 113 | 114 | if projectSettings? 115 | return projectSettings.phpVersion 116 | 117 | return null 118 | -------------------------------------------------------------------------------- /lib/ConstructorGenerationProvider.coffee: -------------------------------------------------------------------------------- 1 | {Point} = require 'atom' 2 | 3 | AbstractProvider = require './AbstractProvider' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # Provides docblock generation and maintenance capabilities. 9 | ## 10 | class DocblockProvider extends AbstractProvider 11 | ###* 12 | * The view that allows the user to select the properties to add to the constructor as parameters. 13 | ### 14 | selectionView: null 15 | 16 | ###* 17 | * Aids in building functions. 18 | ### 19 | functionBuilder: null 20 | 21 | ###* 22 | * The docblock builder. 23 | ### 24 | docblockBuilder: null 25 | 26 | ###* 27 | * The type helper. 28 | ### 29 | typeHelper: null 30 | 31 | ###* 32 | * @param {Object} typeHelper 33 | * @param {Object} functionBuilder 34 | * @param {Object} docblockBuilder 35 | ### 36 | constructor: (@typeHelper, @functionBuilder, @docblockBuilder) -> 37 | 38 | ###* 39 | * @inheritdoc 40 | ### 41 | deactivate: () -> 42 | super() 43 | 44 | if @selectionView 45 | @selectionView.destroy() 46 | @selectionView = null 47 | 48 | ###* 49 | * @inheritdoc 50 | ### 51 | getIntentionProviders: () -> 52 | return [{ 53 | grammarScopes: ['source.php'] 54 | getIntentions: ({textEditor, bufferPosition}) => 55 | return [] if not @getCurrentProjectPhpVersion()? 56 | 57 | return @getIntentions(textEditor, bufferPosition) 58 | }] 59 | 60 | ###* 61 | * @param {TextEditor} editor 62 | * @param {Point} triggerPosition 63 | ### 64 | getIntentions: (editor, triggerPosition) -> 65 | successHandler = (currentClassName) => 66 | return [] if not currentClassName? 67 | 68 | nestedSuccessHandler = (classInfo) => 69 | return [] if not classInfo? 70 | 71 | return [{ 72 | priority : 100 73 | icon : 'gear' 74 | title : 'Generate Constructor' 75 | 76 | selected : () => 77 | items = [] 78 | promises = [] 79 | 80 | localTypesResolvedHandler = (results) => 81 | resultIndex = 0 82 | 83 | for item in items 84 | for type in item.types 85 | type.type = results[resultIndex++] 86 | 87 | zeroBasedStartLine = classInfo.startLine - 1 88 | 89 | tabText = editor.getTabText() 90 | indentationLevel = editor.indentationForBufferRow(triggerPosition.row) 91 | 92 | @generateConstructor( 93 | editor, 94 | triggerPosition, 95 | items, 96 | tabText, 97 | indentationLevel, 98 | atom.config.get('editor.preferredLineLength', editor.getLastCursor().getScopeDescriptor()) 99 | ) 100 | 101 | if classInfo.properties.length == 0 102 | localTypesResolvedHandler([]) 103 | 104 | else 105 | # Ensure all types are localized to the use statements of this file, the original types will be 106 | # relative to the original file (which may not be the same). The FQCN works but is long and 107 | # there may be a local use statement that can be used to shorten it. 108 | for name, property of classInfo.properties 109 | items.push({ 110 | name : name 111 | types : property.types 112 | }) 113 | 114 | for type in property.types 115 | if @typeHelper.isClassType(type.fqcn) 116 | promises.push @service.localizeType( 117 | editor.getPath(), 118 | triggerPosition.row + 1, 119 | type.fqcn 120 | ) 121 | 122 | else 123 | promises.push Promise.resolve(type.fqcn) 124 | 125 | Promise.all(promises).then(localTypesResolvedHandler, failureHandler) 126 | }] 127 | 128 | return @service.getClassInfo(currentClassName).then(nestedSuccessHandler, failureHandler) 129 | 130 | failureHandler = () -> 131 | return [] 132 | 133 | return @service.determineCurrentClassName(editor, triggerPosition).then(successHandler, failureHandler) 134 | 135 | ###* 136 | * @param {TextEditor} editor 137 | * @param {Point} triggerPosition 138 | * @param {Array} items 139 | * @param {String} tabText 140 | * @param {Number} indentationLevel 141 | * @param {Number} maxLineLength 142 | ### 143 | generateConstructor: (editor, triggerPosition, items, tabText, indentationLevel, maxLineLength) -> 144 | metadata = { 145 | editor : editor 146 | position : triggerPosition 147 | tabText : tabText 148 | indentationLevel : indentationLevel 149 | maxLineLength : maxLineLength 150 | } 151 | 152 | if items.length > 0 153 | @getSelectionView().setItems(items) 154 | @getSelectionView().setMetadata(metadata) 155 | @getSelectionView().storeFocusedElement() 156 | @getSelectionView().present() 157 | 158 | else 159 | @onConfirm([], metadata) 160 | 161 | ###* 162 | * Called when the selection of properties is cancelled. 163 | * 164 | * @param {Object|null} metadata 165 | ### 166 | onCancel: (metadata) -> 167 | 168 | ###* 169 | * Called when the selection of properties is confirmed. 170 | * 171 | * @param {array} selectedItems 172 | * @param {Object|null} metadata 173 | ### 174 | onConfirm: (selectedItems, metadata) -> 175 | statements = [] 176 | parameters = [] 177 | docblockParameters = [] 178 | 179 | for item in selectedItems 180 | typeSpecification = @typeHelper.buildTypeSpecificationFromTypeArray(item.types) 181 | parameterTypeHint = @typeHelper.getTypeHintForTypeSpecification(typeSpecification) 182 | 183 | parameters.push({ 184 | name : '$' + item.name 185 | typeHint : parameterTypeHint.typeHint 186 | defaultValue : if parameterTypeHint.shouldSetDefaultValueToNull then 'null' else null 187 | }) 188 | 189 | docblockParameters.push({ 190 | name : '$' + item.name 191 | type : if item.types.length > 0 then typeSpecification else 'mixed' 192 | }) 193 | 194 | statements.push("$this->#{item.name} = $#{item.name};") 195 | 196 | if statements.length == 0 197 | statements.push('') 198 | 199 | functionText = @functionBuilder 200 | .makePublic() 201 | .setIsStatic(false) 202 | .setIsAbstract(false) 203 | .setName('__construct') 204 | .setReturnType(null) 205 | .setParameters(parameters) 206 | .setStatements(statements) 207 | .setTabText(metadata.tabText) 208 | .setIndentationLevel(metadata.indentationLevel) 209 | .setMaxLineLength(metadata.maxLineLength) 210 | .build() 211 | 212 | docblockText = @docblockBuilder.buildForMethod( 213 | docblockParameters, 214 | null, 215 | false, 216 | metadata.tabText.repeat(metadata.indentationLevel) 217 | ) 218 | 219 | text = docblockText.trimLeft() + functionText 220 | 221 | metadata.editor.getBuffer().insert(metadata.position, text) 222 | 223 | ###* 224 | * @return {Builder} 225 | ### 226 | getSelectionView: () -> 227 | if not @selectionView? 228 | View = require './ConstructorGenerationProvider/View' 229 | 230 | @selectionView = new View(@onConfirm.bind(this), @onCancel.bind(this)) 231 | @selectionView.setLoading('Loading class information...') 232 | @selectionView.setEmptyMessage('No properties found.') 233 | 234 | return @selectionView 235 | -------------------------------------------------------------------------------- /lib/ConstructorGenerationProvider/View.coffee: -------------------------------------------------------------------------------- 1 | {$, $$, SelectListView} = require 'atom-space-pen-views' 2 | 3 | MultiSelectionView = require '../Utility/MultiSelectionView.coffee' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # An extension on SelectListView from atom-space-pen-views that allows multiple selections. 9 | ## 10 | class View extends MultiSelectionView 11 | ###* 12 | * @inheritdoc 13 | ### 14 | createWidgets: () -> 15 | checkboxBar = $$ -> 16 | @div class: 'checkbox-bar settings-view', => 17 | @div class: 'controls', => 18 | @div class: 'block text-line', => 19 | @label class: 'icon icon-info', 'Tip: The order in which items are selected determines the order of the output.' 20 | 21 | checkboxBar.appendTo(this) 22 | 23 | # Ensure that button clicks are actually handled. 24 | @on 'mousedown', ({target}) => 25 | return false if $(target).hasClass('checkbox-input') 26 | return false if $(target).hasClass('checkbox-label-text') 27 | 28 | super() 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | invokeOnDidConfirm: () -> 34 | if @onDidConfirm 35 | @onDidConfirm(@selectedItems, @getMetadata()) 36 | -------------------------------------------------------------------------------- /lib/DocblockProvider.coffee: -------------------------------------------------------------------------------- 1 | {Point} = require 'atom' 2 | 3 | AbstractProvider = require './AbstractProvider' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # Provides docblock generation and maintenance capabilities. 9 | ## 10 | class DocblockProvider extends AbstractProvider 11 | ###* 12 | * The docblock builder. 13 | ### 14 | docblockBuilder: null 15 | 16 | ###* 17 | * The type helper. 18 | ### 19 | typeHelper: null 20 | 21 | ###* 22 | * @param {Object} typeHelper 23 | * @param {Object} docblockBuilder 24 | ### 25 | constructor: (@typeHelper, @docblockBuilder) -> 26 | 27 | ###* 28 | * @inheritdoc 29 | ### 30 | getIntentionProviders: () -> 31 | return [{ 32 | grammarScopes: ['entity.name.type.class.php', 'entity.name.type.interface.php', 'entity.name.type.trait.php'] 33 | getIntentions: ({textEditor, bufferPosition}) => 34 | nameRange = textEditor.bufferRangeForScopeAtCursor('entity.name.type') 35 | 36 | return if not nameRange? 37 | return [] if not @getCurrentProjectPhpVersion()? 38 | 39 | name = textEditor.getTextInBufferRange(nameRange) 40 | 41 | return @getClasslikeIntentions(textEditor, bufferPosition, name) 42 | }, { 43 | grammarScopes: ['entity.name.function.php', 'support.function.magic.php'] 44 | getIntentions: ({textEditor, bufferPosition}) => 45 | nameRange = textEditor.bufferRangeForScopeAtCursor('entity.name.function.php') 46 | 47 | if not nameRange? 48 | nameRange = textEditor.bufferRangeForScopeAtCursor('support.function.magic.php') 49 | 50 | return if not nameRange? 51 | return [] if not @getCurrentProjectPhpVersion()? 52 | 53 | name = textEditor.getTextInBufferRange(nameRange) 54 | 55 | return @getFunctionlikeIntentions(textEditor, bufferPosition, name) 56 | }, { 57 | grammarScopes: ['variable.other.php'] 58 | getIntentions: ({textEditor, bufferPosition}) => 59 | nameRange = textEditor.bufferRangeForScopeAtCursor('variable.other.php') 60 | 61 | return if not nameRange? 62 | return [] if not @getCurrentProjectPhpVersion()? 63 | 64 | name = textEditor.getTextInBufferRange(nameRange) 65 | 66 | return @getPropertyIntentions(textEditor, bufferPosition, name) 67 | }, { 68 | grammarScopes: ['constant.other.php'] 69 | getIntentions: ({textEditor, bufferPosition}) => 70 | nameRange = textEditor.bufferRangeForScopeAtCursor('constant.other.php') 71 | 72 | return if not nameRange? 73 | return [] if not @getCurrentProjectPhpVersion()? 74 | 75 | name = textEditor.getTextInBufferRange(nameRange) 76 | 77 | return @getConstantIntentions(textEditor, bufferPosition, name) 78 | }] 79 | 80 | ###* 81 | * @inheritdoc 82 | ### 83 | deactivate: () -> 84 | super() 85 | 86 | if @docblockBuilder 87 | #@docblockBuilder.destroy() 88 | @docblockBuilder = null 89 | 90 | ###* 91 | * @param {TextEditor} editor 92 | * @param {Point} triggerPosition 93 | * @param {String} name 94 | ### 95 | getClasslikeIntentions: (editor, triggerPosition, name) -> 96 | failureHandler = () -> 97 | return [] 98 | 99 | successHandler = (resolvedType) => 100 | nestedSuccessHandler = (classInfo) => 101 | intentions = [] 102 | 103 | return intentions if not classInfo? 104 | 105 | if not classInfo.hasDocblock 106 | if classInfo.hasDocumentation 107 | intentions.push({ 108 | priority : 100 109 | icon : 'gear' 110 | title : 'Generate Docblock (inheritDoc)' 111 | 112 | selected : () => 113 | @generateDocblockInheritance(editor, triggerPosition) 114 | }) 115 | 116 | intentions.push({ 117 | priority : 100 118 | icon : 'gear' 119 | title : 'Generate Docblock' 120 | 121 | selected : () => 122 | @generateClasslikeDocblockFor(editor, classInfo) 123 | }) 124 | 125 | return intentions 126 | 127 | return @service.getClassInfo(resolvedType).then(nestedSuccessHandler, failureHandler) 128 | 129 | return @service.resolveType(editor.getPath(), triggerPosition.row + 1, name, 'classlike').then(successHandler, failureHandler) 130 | 131 | ###* 132 | * @param {TextEditor} editor 133 | * @param {Object} classData 134 | ### 135 | generateClasslikeDocblockFor: (editor, classData) -> 136 | zeroBasedStartLine = classData.startLine - 1 137 | 138 | indentationLevel = editor.indentationForBufferRow(zeroBasedStartLine) 139 | 140 | docblock = @docblockBuilder.buildByLines( 141 | [], 142 | editor.getTabText().repeat(indentationLevel) 143 | ) 144 | 145 | editor.getBuffer().insert(new Point(zeroBasedStartLine, -1), docblock) 146 | 147 | ###* 148 | * @param {TextEditor} editor 149 | * @param {Point} triggerPosition 150 | * @param {String} name 151 | ### 152 | getFunctionlikeIntentions: (editor, triggerPosition, name) -> 153 | failureHandler = () => 154 | return [] 155 | 156 | successHandler = (currentClassName) => 157 | helperFunction = (functionlikeData) => 158 | intentions = [] 159 | 160 | return intentions if not functionlikeData 161 | 162 | if not functionlikeData.hasDocblock 163 | if functionlikeData.hasDocumentation 164 | intentions.push({ 165 | priority : 100 166 | icon : 'gear' 167 | title : 'Generate Docblock (inheritDoc)' 168 | 169 | selected : () => 170 | @generateDocblockInheritance(editor, triggerPosition) 171 | }) 172 | 173 | intentions.push({ 174 | priority : 100 175 | icon : 'gear' 176 | title : 'Generate Docblock' 177 | 178 | selected : () => 179 | @generateFunctionlikeDocblockFor(editor, functionlikeData) 180 | }) 181 | 182 | return intentions 183 | 184 | if currentClassName 185 | nestedSuccessHandler = (classInfo) => 186 | return [] if not name of classInfo.methods 187 | return helperFunction(classInfo.methods[name]) 188 | 189 | @service.getClassInfo(currentClassName).then(nestedSuccessHandler, failureHandler) 190 | 191 | else 192 | nestedSuccessHandler = (globalFunctions) => 193 | return [] if not name of globalFunctions 194 | return helperFunction(globalFunctions[name]) 195 | 196 | @service.getGlobalFunctions().then(nestedSuccessHandler, failureHandler) 197 | 198 | @service.determineCurrentClassName(editor, triggerPosition).then(successHandler, failureHandler) 199 | 200 | ###* 201 | * @param {TextEditor} editor 202 | * @param {Object} data 203 | ### 204 | generateFunctionlikeDocblockFor: (editor, data) -> 205 | zeroBasedStartLine = data.startLine - 1 206 | 207 | parameters = data.parameters.map (parameter) => 208 | type = 'mixed' 209 | 210 | if parameter.types.length > 0 211 | type = @typeHelper.buildTypeSpecificationFromTypeArray(parameter.types) 212 | 213 | name = '' 214 | 215 | if parameter.isReference 216 | name += '&' 217 | 218 | name += '$' + parameter.name 219 | 220 | if parameter.isVariadic 221 | name = '...' + name 222 | type += '[]' 223 | 224 | return { 225 | name: name 226 | type: type 227 | } 228 | 229 | indentationLevel = editor.indentationForBufferRow(zeroBasedStartLine) 230 | 231 | returnType = null 232 | 233 | if data.returnTypes.length > 0 and data.name != '__construct' 234 | returnType = @typeHelper.buildTypeSpecificationFromTypeArray(data.returnTypes) 235 | 236 | docblock = @docblockBuilder.buildForMethod( 237 | parameters, 238 | returnType, 239 | false, 240 | editor.getTabText().repeat(indentationLevel) 241 | ) 242 | 243 | editor.getBuffer().insert(new Point(zeroBasedStartLine, -1), docblock) 244 | 245 | ###* 246 | * @param {TextEditor} editor 247 | * @param {Point} triggerPosition 248 | * @param {String} name 249 | ### 250 | getPropertyIntentions: (editor, triggerPosition, name) -> 251 | failureHandler = () => 252 | return [] 253 | 254 | successHandler = (currentClassName) => 255 | return [] if not currentClassName? 256 | 257 | nestedSuccessHandler = (classInfo) => 258 | name = name.substr(1) 259 | 260 | return [] if not name of classInfo.properties 261 | 262 | propertyData = classInfo.properties[name] 263 | 264 | return if not propertyData? 265 | 266 | intentions = [] 267 | 268 | return intentions if not propertyData 269 | 270 | if not propertyData.hasDocblock 271 | if propertyData.hasDocumentation 272 | intentions.push({ 273 | priority : 100 274 | icon : 'gear' 275 | title : 'Generate Docblock (inheritDoc)' 276 | 277 | selected : () => 278 | @generateDocblockInheritance(editor, triggerPosition) 279 | }) 280 | 281 | intentions.push({ 282 | priority : 100 283 | icon : 'gear' 284 | title : 'Generate Docblock' 285 | 286 | selected : () => 287 | @generatePropertyDocblockFor(editor, propertyData) 288 | }) 289 | 290 | return intentions 291 | 292 | @service.getClassInfo(currentClassName).then(nestedSuccessHandler, failureHandler) 293 | 294 | @service.determineCurrentClassName(editor, triggerPosition).then(successHandler, failureHandler) 295 | 296 | ###* 297 | * @param {TextEditor} editor 298 | * @param {Object} data 299 | ### 300 | generatePropertyDocblockFor: (editor, data) -> 301 | zeroBasedStartLine = data.startLine - 1 302 | 303 | indentationLevel = editor.indentationForBufferRow(zeroBasedStartLine) 304 | 305 | type = 'mixed' 306 | 307 | if data.types.length > 0 308 | type = @typeHelper.buildTypeSpecificationFromTypeArray(data.types) 309 | 310 | docblock = @docblockBuilder.buildForProperty( 311 | type, 312 | false, 313 | editor.getTabText().repeat(indentationLevel) 314 | ) 315 | 316 | editor.getBuffer().insert(new Point(zeroBasedStartLine, -1), docblock) 317 | 318 | ###* 319 | * @param {TextEditor} editor 320 | * @param {Point} triggerPosition 321 | * @param {String} name 322 | ### 323 | getConstantIntentions: (editor, triggerPosition, name) -> 324 | failureHandler = () => 325 | return [] 326 | 327 | successHandler = (currentClassName) => 328 | helperFunction = (constantData) => 329 | intentions = [] 330 | 331 | return intentions if not constantData 332 | 333 | if not constantData.hasDocblock 334 | intentions.push({ 335 | priority : 100 336 | icon : 'gear' 337 | title : 'Generate Docblock' 338 | 339 | selected : () => 340 | @generateConstantDocblockFor(editor, constantData) 341 | }) 342 | 343 | return intentions 344 | 345 | if currentClassName 346 | nestedSuccessHandler = (classInfo) => 347 | return [] if not name of classInfo.constants 348 | return helperFunction(classInfo.constants[name]) 349 | 350 | @service.getClassInfo(currentClassName).then(nestedSuccessHandler, failureHandler) 351 | 352 | else 353 | nestedSuccessHandler = (globalConstants) => 354 | return [] if not name of globalConstants 355 | return helperFunction(globalConstants[name]) 356 | 357 | @service.getGlobalConstants().then(nestedSuccessHandler, failureHandler) 358 | 359 | @service.determineCurrentClassName(editor, triggerPosition).then(successHandler, failureHandler) 360 | 361 | ###* 362 | * @param {TextEditor} editor 363 | * @param {Object} data 364 | ### 365 | generateConstantDocblockFor: (editor, data) -> 366 | zeroBasedStartLine = data.startLine - 1 367 | 368 | indentationLevel = editor.indentationForBufferRow(zeroBasedStartLine) 369 | 370 | type = 'mixed' 371 | 372 | if data.types.length > 0 373 | type = @typeHelper.buildTypeSpecificationFromTypeArray(data.types) 374 | 375 | docblock = @docblockBuilder.buildForProperty( 376 | type, 377 | false, 378 | editor.getTabText().repeat(indentationLevel) 379 | ) 380 | 381 | editor.getBuffer().insert(new Point(zeroBasedStartLine, -1), docblock) 382 | 383 | ###* 384 | * @param {TextEditor} editor 385 | * @param {Point} triggerPosition 386 | ### 387 | generateDocblockInheritance: (editor, triggerPosition) -> 388 | indentationLevel = editor.indentationForBufferRow(triggerPosition.row) 389 | 390 | docblock = @docblockBuilder.buildByLines( 391 | ['@inheritDoc'], 392 | editor.getTabText().repeat(indentationLevel) 393 | ) 394 | 395 | editor.getBuffer().insert(new Point(triggerPosition.row, -1), docblock) 396 | -------------------------------------------------------------------------------- /lib/ExtractMethodProvider.coffee: -------------------------------------------------------------------------------- 1 | {Range} = require 'atom' 2 | 3 | AbstractProvider = require './AbstractProvider' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # Provides method extraction capabilities. 9 | ## 10 | class ExtractMethodProvider extends AbstractProvider 11 | ###* 12 | * View that the user interacts with when extracting code. 13 | * 14 | * @type {Object} 15 | ### 16 | view: null 17 | 18 | ###* 19 | * Builder used to generate the new method. 20 | * 21 | * @type {Object} 22 | ### 23 | builder: null 24 | 25 | ###* 26 | * @param {Object} builder 27 | ### 28 | constructor: (@builder) -> 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | activate: (service) -> 34 | super(service) 35 | 36 | atom.commands.add 'atom-text-editor', "php-integrator-refactoring:extract-method": => 37 | @executeCommand() 38 | 39 | ###* 40 | * @inheritdoc 41 | ### 42 | deactivate: () -> 43 | super() 44 | 45 | if @view 46 | @view.destroy() 47 | @view = null 48 | 49 | ###* 50 | * @inheritdoc 51 | ### 52 | getIntentionProviders: () -> 53 | return [{ 54 | grammarScopes: ['source.php'] 55 | getIntentions: ({textEditor, bufferPosition}) => 56 | activeTextEditor = atom.workspace.getActiveTextEditor() 57 | 58 | return [] if not activeTextEditor 59 | return [] if not @getCurrentProjectPhpVersion()? 60 | 61 | selection = activeTextEditor.getSelectedBufferRange() 62 | 63 | # Checking if a selection has been made 64 | if selection.start.row == selection.end.row and selection.start.column == selection.end.column 65 | return [] 66 | 67 | return [ 68 | { 69 | priority : 200 70 | icon : 'git-branch' 71 | title : 'Extract Method' 72 | 73 | selected : () => 74 | @executeCommand() 75 | } 76 | ] 77 | }] 78 | 79 | ###* 80 | * Executes the extraction. 81 | ### 82 | executeCommand: () -> 83 | activeTextEditor = atom.workspace.getActiveTextEditor() 84 | 85 | return if not activeTextEditor 86 | 87 | tabText = activeTextEditor.getTabText() 88 | 89 | selection = activeTextEditor.getSelectedBufferRange() 90 | 91 | # Checking if a selection has been made 92 | if selection.start.row == selection.end.row and selection.start.column == selection.end.column 93 | atom.notifications.addInfo('php-integrator-refactoring', { 94 | detail: 'Please select the code to extract and try again.' 95 | }) 96 | 97 | return 98 | 99 | line = activeTextEditor.lineTextForBufferRow(selection.start.row) 100 | 101 | findSingleTab = new RegExp("(#{tabText})", "g") 102 | 103 | matches = (line.match(findSingleTab) || []).length 104 | 105 | # If the first line doesn't have any tabs then add one. 106 | highlightedText = activeTextEditor.getTextInBufferRange(selection) 107 | selectedBufferFirstLine = highlightedText.split("\n")[0] 108 | 109 | if (selectedBufferFirstLine.match(findSingleTab) || []).length == 0 110 | highlightedText = "#{tabText}" + highlightedText 111 | 112 | # Replacing double indents with one, so it can be shown in the preview area of panel. 113 | multipleTabTexts = Array(matches).fill("#{tabText}") 114 | findMultipleTab = new RegExp("^" + multipleTabTexts.join(''), "mg") 115 | reducedHighlightedText = highlightedText.replace(findMultipleTab, "#{tabText}") 116 | 117 | @builder.setEditor(activeTextEditor) 118 | @builder.setMethodBody(reducedHighlightedText) 119 | 120 | @getView().storeFocusedElement() 121 | @getView().present() 122 | 123 | ###* 124 | * Called when the user has cancel the extraction in the modal. 125 | ### 126 | onCancel: -> 127 | @builder.cleanUp() 128 | 129 | ###* 130 | * Called when the user has confirmed the extraction in the modal. 131 | * 132 | * @param {Object} settings 133 | * 134 | * @see ParameterParser.buildMethod for structure of settings 135 | ### 136 | onConfirm: (settings) -> 137 | successHandler = (methodCall) => 138 | activeTextEditor = atom.workspace.getActiveTextEditor() 139 | 140 | selectedBufferRange = activeTextEditor.getSelectedBufferRange() 141 | 142 | highlightedBufferPosition = selectedBufferRange.end 143 | 144 | row = 0 145 | 146 | loop 147 | row++ 148 | descriptions = activeTextEditor.scopeDescriptorForBufferPosition( 149 | [highlightedBufferPosition.row + row, activeTextEditor.getTabLength()] 150 | ) 151 | indexOfDescriptor = descriptions.scopes.indexOf('punctuation.section.scope.end.php') 152 | break if indexOfDescriptor > -1 || row == activeTextEditor.getLineCount() 153 | 154 | row = highlightedBufferPosition.row + row 155 | 156 | line = activeTextEditor.lineTextForBufferRow row 157 | 158 | endOfLine = line?.length 159 | 160 | replaceRange = [ 161 | [row, 0], 162 | [row, endOfLine] 163 | ] 164 | 165 | previousText = activeTextEditor.getTextInBufferRange replaceRange 166 | 167 | settings.tabs = true 168 | 169 | nestedSuccessHandler = (newMethodBody) => 170 | settings.tabs = false 171 | 172 | @builder.cleanUp() 173 | 174 | activeTextEditor.transact () => 175 | # Matching current indentation 176 | selectedText = activeTextEditor.getSelectedText() 177 | spacing = selectedText.match /^\s*/ 178 | if spacing != null 179 | spacing = spacing[0] 180 | 181 | activeTextEditor.insertText(spacing + methodCall) 182 | 183 | # Remove any extra new lines between functions 184 | nextLine = activeTextEditor.lineTextForBufferRow row + 1 185 | if nextLine == '' 186 | activeTextEditor.setSelectedBufferRange( 187 | [ 188 | [row + 1, 0], 189 | [row + 1, 1] 190 | ] 191 | ) 192 | activeTextEditor.deleteLine() 193 | 194 | 195 | # Re working out range as inserting method call will delete some 196 | # lines and thus offsetting this 197 | row -= selectedBufferRange.end.row - selectedBufferRange.start.row 198 | 199 | if @snippetManager? 200 | activeTextEditor.setCursorBufferPosition [row + 1, 0] 201 | 202 | body = "\n#{newMethodBody}" 203 | 204 | result = @getTabStopsForBody body 205 | 206 | snippet = { 207 | body: body, 208 | lineCount: result.lineCount, 209 | tabStops: result.tabStops 210 | } 211 | 212 | @snippetManager.insertSnippet( 213 | snippet, 214 | activeTextEditor 215 | ) 216 | else 217 | # Re working out range as inserting method call will delete some 218 | # lines and thus offsetting this 219 | row -= selectedBufferRange.end.row - selectedBufferRange.start.row 220 | 221 | replaceRange = [ 222 | [row, 0], 223 | [row, line?.length] 224 | ] 225 | 226 | activeTextEditor.setTextInBufferRange( 227 | replaceRange, 228 | "#{previousText}\n\n#{newMethodBody}" 229 | ) 230 | 231 | nestedFailureHandler = () => 232 | settings.tabs = false 233 | 234 | @builder.buildMethod(settings).then(nestedSuccessHandler, nestedFailureHandler) 235 | 236 | failureHandler = () => 237 | # Do nothing. 238 | 239 | @builder.buildMethodCall(settings.methodName).then(successHandler, failureHandler) 240 | 241 | ###* 242 | * Gets all the tab stops and line count for the body given 243 | * 244 | * @param {String} body 245 | * 246 | * @return {Object} 247 | ### 248 | getTabStopsForBody: (body) -> 249 | lines = body.split "\n" 250 | row = 0 251 | lineCount = 0 252 | tabStops = [] 253 | tabStopIndex = {} 254 | 255 | for line in lines 256 | regex = /(\[[\w ]*?\])(\s*\$[a-zA-Z0-9_]+)?/g 257 | # Get tab stops by looping through all matches 258 | while (match = regex.exec(line)) != null 259 | key = match[2] # 2nd capturing group (variable name) 260 | replace = match[1] # 1st capturing group ([type]) 261 | range = new Range( 262 | [row, match.index], 263 | [row, match.index + match[1].length] 264 | ) 265 | 266 | if key != undefined 267 | key = key.trim() 268 | if tabStopIndex[key] != undefined 269 | tabStopIndex[key].push range 270 | else 271 | tabStopIndex[key] = [range] 272 | else 273 | tabStops.push [range] 274 | 275 | row++ 276 | lineCount++ 277 | 278 | for objectKey in Object.keys(tabStopIndex) 279 | tabStops.push tabStopIndex[objectKey] 280 | 281 | tabStops = tabStops.sort @sortTabStops 282 | 283 | return { 284 | tabStops: tabStops, 285 | lineCount: lineCount 286 | } 287 | 288 | ###* 289 | * Sorts the tab stops by their row and column 290 | * 291 | * @param {Array} a 292 | * @param {Array} b 293 | * 294 | * @return {Integer} 295 | ### 296 | sortTabStops: (a, b) -> 297 | # Grabbing first range in the array 298 | a = a[0] 299 | b = b[0] 300 | 301 | # b is before a in the rows 302 | if a.start.row > b.start.row 303 | return 1 304 | 305 | # a is before b in the rows 306 | if a.start.row < b.start.row 307 | return -1 308 | 309 | # On same line but b is before a 310 | if a.start.column > b.start.column 311 | return 1 312 | 313 | # On same line but a is before b 314 | if a.start.column < b.start.column 315 | return -1 316 | 317 | # Same position 318 | return 0 319 | 320 | ###* 321 | * @return {View} 322 | ### 323 | getView: () -> 324 | if not @view? 325 | View = require './ExtractMethodProvider/View' 326 | 327 | @view = new View(@onConfirm.bind(this), @onCancel.bind(this)) 328 | @view.setBuilder(@builder) 329 | 330 | return @view 331 | -------------------------------------------------------------------------------- /lib/ExtractMethodProvider/Builder.coffee: -------------------------------------------------------------------------------- 1 | {Range} = require 'atom' 2 | 3 | module.exports = 4 | 5 | class Builder 6 | ###* 7 | * The body of the new method that will be shown in the preview area. 8 | * 9 | * @type {String} 10 | ### 11 | methodBody: '' 12 | 13 | ###* 14 | * The tab string that is used by the current editor. 15 | * 16 | * @type {String} 17 | ### 18 | tabText: '' 19 | 20 | ###* 21 | * @type {Number} 22 | ### 23 | indentationLevel: null 24 | 25 | ###* 26 | * @type {Number} 27 | ### 28 | maxLineLength: null 29 | 30 | ###* 31 | * The php-integrator-base service. 32 | * 33 | * @type {Service} 34 | ### 35 | service: null 36 | 37 | ###* 38 | * A range of the selected/highlighted area of code to analyse. 39 | * 40 | * @type {Range} 41 | ### 42 | selectedBufferRange: null 43 | 44 | ###* 45 | * The text editor to be analysing. 46 | * 47 | * @type {TextEditor} 48 | ### 49 | editor: null 50 | 51 | ###* 52 | * The parameter parser that will work out the parameters the 53 | * selectedBufferRange will need. 54 | * 55 | * @type {Object} 56 | ### 57 | parameterParser: null 58 | 59 | ###* 60 | * All the variables to return 61 | * 62 | * @type {Array} 63 | ### 64 | returnVariables: null 65 | 66 | ###* 67 | * @type {Object} 68 | ### 69 | docblockBuilder: null 70 | 71 | ###* 72 | * @type {Object} 73 | ### 74 | functionBuilder: null 75 | 76 | ###* 77 | * @type {Object} 78 | ### 79 | typeHelper: null 80 | 81 | ###* 82 | * Constructor. 83 | * 84 | * @param {Object} parameterParser 85 | * @param {Object} docblockBuilder 86 | * @param {Object} functionBuilder 87 | * @param {Object} typeHelper 88 | ### 89 | constructor: (@parameterParser, @docblockBuilder, @functionBuilder, @typeHelper) -> 90 | 91 | ###* 92 | * Sets the method body to use in the preview. 93 | * 94 | * @param {String} text 95 | ### 96 | setMethodBody: (text) -> 97 | @methodBody = text 98 | 99 | ###* 100 | * The tab string to use when generating the new method. 101 | * 102 | * @param {String} tab 103 | ### 104 | setTabText: (tab) -> 105 | @tabText = tab 106 | 107 | ###* 108 | * @param {Number} indentationLevel 109 | ### 110 | setIndentationLevel: (indentationLevel) -> 111 | @indentationLevel = indentationLevel 112 | 113 | ###* 114 | * @param {Number} maxLineLength 115 | ### 116 | setMaxLineLength: (maxLineLength) -> 117 | @maxLineLength = maxLineLength 118 | 119 | ###* 120 | * Set the php-integrator-base service to be used. 121 | * 122 | * @param {Service} service 123 | ### 124 | setService: (service) -> 125 | @service = service 126 | @parameterParser.setService(service) 127 | 128 | ###* 129 | * Set the selectedBufferRange to analyse. 130 | * 131 | * @param {Range} range [description] 132 | ### 133 | setSelectedBufferRange: (range) -> 134 | @selectedBufferRange = range 135 | 136 | ###* 137 | * Set the TextEditor to be used when analysing the selectedBufferRange 138 | * 139 | * @param {TextEditor} editor [description] 140 | ### 141 | setEditor: (editor) => 142 | @editor = editor 143 | @setTabText(editor.getTabText()) 144 | @setIndentationLevel(1) 145 | @setMaxLineLength(atom.config.get('editor.preferredLineLength', editor.getLastCursor().getScopeDescriptor())) 146 | @setSelectedBufferRange(editor.getSelectedBufferRange()) 147 | 148 | ###* 149 | * Builds the new method from the selectedBufferRange and settings given. 150 | * 151 | * The settings parameter should be an object with these properties: 152 | * - methodName (string) 153 | * - visibility (string) ['private', 'protected', 'public'] 154 | * - tabs (boolean) 155 | * - generateDocs (boolean) 156 | * - arraySyntax (string) ['word', 'brackets'] 157 | * - generateDocPlaceholders (boolean) 158 | * 159 | * @param {Object} settings 160 | * 161 | * @return {Promise} 162 | ### 163 | buildMethod: (settings) => 164 | successHandler = (parameters) => 165 | if @returnVariables == null 166 | @returnVariables = @workOutReturnVariables @parameterParser.getVariableDeclarations() 167 | 168 | tabText = if settings.tabs then @tabText else '' 169 | totalIndentation = tabText.repeat(@indentationLevel) 170 | 171 | statements = [] 172 | 173 | for statement in @methodBody.split('\n') 174 | newStatement = statement.substr(totalIndentation.length) 175 | 176 | statements.push(newStatement) 177 | 178 | returnTypeHintSpecification = 'void' 179 | returnStatement = @buildReturnStatement(@returnVariables, settings.arraySyntax) 180 | 181 | if returnStatement? 182 | if @returnVariables.length == 1 183 | returnTypeHintSpecification = @returnVariables[0].types.join('|') 184 | 185 | else 186 | returnTypeHintSpecification = 'array' 187 | 188 | returnStatement = returnStatement.substr(totalIndentation.length) 189 | 190 | statements.push('') 191 | statements.push(returnStatement) 192 | 193 | functionParameters = parameters.map (parameter) => 194 | typeHintInfo = @typeHelper.getTypeHintForDocblockTypes(parameter.types) 195 | 196 | return { 197 | name : parameter.name 198 | typeHint : if typeHintInfo? and settings.typeHinting then typeHintInfo.typeHint else null 199 | defaultValue : if typeHintInfo? and typeHintInfo.isNullable then 'null' else null 200 | } 201 | 202 | docblockParameters = parameters.map (parameter) => 203 | typeSpecification = @typeHelper.buildTypeSpecificationFromTypes(parameter.types) 204 | 205 | return { 206 | name : parameter.name 207 | type : if typeSpecification.length > 0 then typeSpecification else '[type]' 208 | } 209 | 210 | @functionBuilder 211 | .setIsStatic(false) 212 | .setIsAbstract(false) 213 | .setName(settings.methodName) 214 | .setReturnType(@typeHelper.getReturnTypeHintForTypeSpecification(returnTypeHintSpecification)) 215 | .setParameters(functionParameters) 216 | .setStatements(statements) 217 | .setIndentationLevel(@indentationLevel) 218 | .setTabText(tabText) 219 | .setMaxLineLength(@maxLineLength) 220 | 221 | if settings.visibility == 'public' 222 | @functionBuilder.makePublic() 223 | 224 | else if settings.visibility == 'protected' 225 | @functionBuilder.makeProtected() 226 | 227 | else if settings.visibility == 'private' 228 | @functionBuilder.makePrivate() 229 | 230 | else 231 | @functionBuilder.makeGlobal() 232 | 233 | docblockText = '' 234 | 235 | if settings.generateDocs 236 | returnType = 'void' 237 | 238 | if @returnVariables != null && @returnVariables.length > 0 239 | returnType = '[type]' 240 | 241 | if @returnVariables.length > 1 242 | returnType = 'array' 243 | 244 | else if @returnVariables.length == 1 and @returnVariables[0].types.length > 0 245 | returnType = @typeHelper.buildTypeSpecificationFromTypes(@returnVariables[0].types) 246 | 247 | docblockText = @docblockBuilder.buildForMethod( 248 | docblockParameters, 249 | returnType, 250 | settings.generateDescPlaceholders, 251 | totalIndentation 252 | ) 253 | 254 | return docblockText + @functionBuilder.build() 255 | 256 | failureHandler = () -> 257 | return null 258 | 259 | return @parameterParser.findParameters(@editor, @selectedBufferRange).then(successHandler, failureHandler) 260 | 261 | ###* 262 | * Build the line that calls the new method and the variable the method 263 | * to be assigned to. 264 | * 265 | * @param {String} methodName 266 | * @param {String} variable [Optional] 267 | * 268 | * @return {Promise} 269 | ### 270 | buildMethodCall: (methodName, variable) => 271 | successHandler = (parameters) => 272 | parameterNames = parameters.map (item) -> 273 | return item.name 274 | 275 | methodCall = "$this->#{methodName}(#{parameterNames.join ', '});" 276 | 277 | if variable != undefined 278 | methodCall = "$#{variable} = #{methodCall}" 279 | else 280 | if @returnVariables != null 281 | if @returnVariables.length == 1 282 | methodCall = "#{@returnVariables[0].name} = #{methodCall}" 283 | else if @returnVariables.length > 1 284 | variables = @returnVariables.reduce (previous, current) -> 285 | if typeof previous != 'string' 286 | previous = previous.name 287 | 288 | return previous + ', ' + current.name 289 | 290 | methodCall = "list(#{variables}) = #{methodCall}" 291 | 292 | return methodCall 293 | 294 | failureHandler = () -> 295 | return null 296 | 297 | @parameterParser.findParameters(@editor, @selectedBufferRange).then(successHandler, failureHandler) 298 | 299 | ###* 300 | * Performs any clean up needed with the builder. 301 | ### 302 | cleanUp: -> 303 | @returnVariables = null 304 | @parameterParser.cleanUp() 305 | 306 | ###* 307 | * Works out which variables need to be returned from the new method. 308 | * 309 | * @param {Array} variableDeclarations 310 | * 311 | * @return {Array} 312 | ### 313 | workOutReturnVariables: (variableDeclarations) -> 314 | startPoint = @selectedBufferRange.end 315 | scopeRange = @parameterParser.getRangeForCurrentScope(@editor, startPoint) 316 | 317 | lookupRange = new Range(startPoint, scopeRange.end) 318 | 319 | textAfterExtraction = @editor.getTextInBufferRange lookupRange 320 | allVariablesAfterExtraction = textAfterExtraction.match /\$[a-zA-Z0-9]+/g 321 | 322 | return null if allVariablesAfterExtraction == null 323 | 324 | variableDeclarations = variableDeclarations.filter (variable) => 325 | return true if variable.name in allVariablesAfterExtraction 326 | return false 327 | 328 | return variableDeclarations 329 | 330 | ###* 331 | * Builds the return statement for the new method. 332 | * 333 | * @param {Array} variableDeclarations 334 | * @param {String} arrayType ['word', 'brackets'] 335 | * 336 | * @return {String|null} 337 | ### 338 | buildReturnStatement: (variableDeclarations, arrayType = 'word') -> 339 | if variableDeclarations? 340 | if variableDeclarations.length == 1 341 | return "#{@tabText}return #{variableDeclarations[0].name};" 342 | 343 | else if variableDeclarations.length > 1 344 | variables = variableDeclarations.reduce (previous, current) -> 345 | if typeof previous != 'string' 346 | previous = previous.name 347 | 348 | return previous + ', ' + current.name 349 | 350 | if arrayType == 'brackets' 351 | variables = "[#{variables}]" 352 | 353 | else 354 | variables = "array(#{variables})" 355 | 356 | return "#{@tabText}return #{variables};" 357 | 358 | return null 359 | 360 | ###* 361 | * Checks if the new method will be returning any values. 362 | * 363 | * @return {Boolean} 364 | ### 365 | hasReturnValues: -> 366 | return @returnVariables != null && @returnVariables.length > 0 367 | 368 | ###* 369 | * Returns if there are multiple return values. 370 | * 371 | * @return {Boolean} 372 | ### 373 | hasMultipleReturnValues: -> 374 | return @returnVariables != null && @returnVariables.length > 1 375 | -------------------------------------------------------------------------------- /lib/ExtractMethodProvider/ParameterParser.coffee: -------------------------------------------------------------------------------- 1 | {Point, Range} = require 'atom' 2 | 3 | module.exports = 4 | 5 | class ParameterParser 6 | ###* 7 | * Service object from the php-integrator-base service 8 | * 9 | * @type {Service} 10 | ### 11 | service: null 12 | 13 | ###* 14 | * @type {Object} 15 | ### 16 | typeHelper: null 17 | 18 | ###* 19 | * List of all the variable declarations that have been process 20 | * 21 | * @type {Array} 22 | ### 23 | variableDeclarations: [] 24 | 25 | ###* 26 | * The selected range that we are scanning for parameters in. 27 | * 28 | * @type {Range} 29 | ### 30 | selectedBufferRange: null 31 | 32 | ###* 33 | * Constructor 34 | * 35 | * @param {Object} typeHelper 36 | ### 37 | constructor: (@typeHelper) -> 38 | 39 | ###* 40 | * @param {Object} service 41 | ### 42 | setService: (@service) -> 43 | 44 | ###* 45 | * Takes the editor and the range and loops through finding all the 46 | * parameters that will be needed if this code was to be moved into 47 | * its own function 48 | * 49 | * @param {TextEditor} editor 50 | * @param {Range} selectedBufferRange 51 | * 52 | * @return {Promise} 53 | ### 54 | findParameters: (editor, selectedBufferRange) -> 55 | @selectedBufferRange = selectedBufferRange 56 | 57 | parameters = [] 58 | 59 | editor.scanInBufferRange /\$[a-zA-Z0-9_]+/g, selectedBufferRange, (element) => 60 | # Making sure we matched a variable and not a variable within a string 61 | descriptions = editor.scopeDescriptorForBufferPosition(element.range.start) 62 | indexOfDescriptor = descriptions.scopes.indexOf('variable.other.php') 63 | if indexOfDescriptor > -1 64 | parameters.push { 65 | name: element.matchText, 66 | range: element.range 67 | } 68 | 69 | regexFilters = [ 70 | { 71 | name: 'Foreach loops', 72 | regex: /as\s(\$[a-zA-Z0-9_]+)(?:\s=>\s(\$[a-zA-Z0-9_]+))?/g 73 | }, 74 | { 75 | name: 'For loops', 76 | regex: /for\s*\(\s*(\$[a-zA-Z0-9_]+)\s*=/g 77 | }, 78 | { 79 | name: 'Try catch', 80 | regex: /catch(?:\(|\s)+.*?(\$[a-zA-Z0-9_]+)/g 81 | }, 82 | { 83 | name: 'Closure' 84 | regex: /function(?:\s)*?\((?:\$).*?\)/g 85 | }, 86 | { 87 | name: 'Variable declarations', 88 | regex: /(\$[a-zA-Z0-9]+)\s*?=(?!>|=)/g 89 | } 90 | ] 91 | 92 | getTypePromises = [] 93 | variableDeclarations = [] 94 | 95 | for filter in regexFilters 96 | editor.backwardsScanInBufferRange filter.regex, selectedBufferRange, (element) => 97 | variables = element.matchText.match /\$[a-zA-Z0-9]+/g 98 | startPoint = new Point(element.range.end.row, 0) 99 | scopeRange = @getRangeForCurrentScope editor, startPoint 100 | 101 | if filter.name == 'Variable declarations' 102 | chosenParameter = null 103 | for parameter in parameters 104 | if element.range.containsRange(parameter.range) 105 | chosenParameter = parameter 106 | break 107 | 108 | if chosenParameter != null 109 | getTypePromises.push (@getTypesForParameter editor, chosenParameter) 110 | variableDeclarations.push chosenParameter 111 | 112 | for variable in variables 113 | parameters = parameters.filter (parameter) => 114 | if parameter.name != variable 115 | return true 116 | if scopeRange.containsRange(parameter.range) 117 | # If variable declaration is after parameter then it's 118 | # still needed in parameters. 119 | if element.range.start.row > parameter.range.start.row 120 | return true 121 | if element.range.start.row == parameter.range.start.row && 122 | element.range.start.column > parameter.range.start.column 123 | return true 124 | 125 | return false 126 | 127 | return true 128 | 129 | @variableDeclarations = @makeUnique variableDeclarations 130 | 131 | parameters = @makeUnique parameters 132 | 133 | # Grab the variable types of the parameters. 134 | promises = [] 135 | 136 | parameters.forEach (parameter) => 137 | # Removing $this from parameters as this doesn't need to be passed in. 138 | return if parameter.name == '$this' 139 | 140 | promises.push @getTypesForParameter(editor, parameter) 141 | 142 | returnFirstResultHandler = (resultArray) -> 143 | return resultArray[0] 144 | 145 | return Promise.all([Promise.all(promises), Promise.all(getTypePromises)]).then(returnFirstResultHandler) 146 | 147 | ###* 148 | * Takes the current buffer position and returns a range of the current 149 | * scope that the buffer position is in. 150 | * 151 | * For example this could be the code within an if statement or closure. 152 | * 153 | * @param {TextEditor} editor 154 | * @param {Point} bufferPosition 155 | * 156 | * @return {Range} 157 | ### 158 | getRangeForCurrentScope: (editor, bufferPosition) -> 159 | startScopePoint = null 160 | endScopePoint = null 161 | 162 | # Tracks any extra scopes that might exist inside the scope we are 163 | # looking for. 164 | childScopes = 0 165 | 166 | # First walk back until we find the start of the current scope. 167 | for row in [bufferPosition.row .. 0] 168 | line = editor.lineTextForBufferRow(row) 169 | 170 | continue if not line 171 | 172 | lastIndex = line.length - 1 173 | 174 | for i in [lastIndex .. 0] 175 | descriptions = editor.scopeDescriptorForBufferPosition( 176 | [row, i] 177 | ) 178 | 179 | indexOfDescriptor = descriptions.scopes.indexOf('punctuation.section.scope.end.php') 180 | if indexOfDescriptor > -1 181 | childScopes++ 182 | 183 | indexOfDescriptor = descriptions.scopes.indexOf('punctuation.section.scope.begin.php') 184 | if indexOfDescriptor > -1 185 | childScopes-- 186 | 187 | if childScopes == -1 188 | startScopePoint = new Point(row, 0) 189 | break 190 | 191 | break if startScopePoint? 192 | 193 | if startScopePoint == null 194 | startScopePoint = new Point(0, 0) 195 | 196 | childScopes = 0 197 | 198 | # Walk forward until we find the end of the current scope 199 | for row in [startScopePoint.row .. editor.getLineCount()] 200 | line = editor.lineTextForBufferRow(row) 201 | 202 | continue if not line 203 | 204 | startIndex = 0 205 | 206 | if startScopePoint.row == row 207 | startIndex = line.length - 1 208 | 209 | for i in [startIndex .. line.length - 1] 210 | descriptions = editor.scopeDescriptorForBufferPosition( 211 | [row, i] 212 | ) 213 | 214 | indexOfDescriptor = descriptions.scopes.indexOf('punctuation.section.scope.begin.php') 215 | if indexOfDescriptor > -1 216 | childScopes++ 217 | 218 | indexOfDescriptor = descriptions.scopes.indexOf('punctuation.section.scope.end.php') 219 | if indexOfDescriptor > -1 220 | if childScopes > 0 221 | childScopes-- 222 | 223 | if childScopes == 0 224 | endScopePoint = new Point(row, i + 1) 225 | break 226 | 227 | break if endScopePoint? 228 | 229 | return new Range(startScopePoint, endScopePoint) 230 | 231 | ###* 232 | * Takes an array of parameters and removes any parameters that appear more 233 | * that once with the same name. 234 | * 235 | * @param {Array} array 236 | * 237 | * @return {Array} 238 | ### 239 | makeUnique: (array) -> 240 | return array.filter (filterItem, pos, self) -> 241 | for i in [0 .. self.length - 1] 242 | if self[i].name != filterItem.name 243 | continue 244 | 245 | return pos == i 246 | return true 247 | ###* 248 | * Generates the key used to store the parameters in the cache. 249 | * 250 | * @param {TextEditor} editor 251 | * @param {Range} selectedBufferRange 252 | * 253 | * @return {String} 254 | ### 255 | buildKey: (editor, selectedBufferRange) -> 256 | return editor.getPath() + JSON.stringify(selectedBufferRange) 257 | 258 | ###* 259 | * Gets the type for the parameter given. 260 | * 261 | * @param {TextEditor} editor 262 | * @param {Object} parameter 263 | * 264 | * @return {Promise} 265 | ### 266 | getTypesForParameter: (editor, parameter) -> 267 | successHandler = (types) => 268 | parameter.types = types 269 | 270 | typeResolutionPromises = [] 271 | path = editor.getPath() 272 | 273 | localizeTypeSuccessHandler = (localizedType) => 274 | return localizedType 275 | 276 | localizeTypeFailureHandler = () -> 277 | return null 278 | 279 | for fqcn in parameter.types 280 | if @typeHelper.isClassType(fqcn) 281 | typeResolutionPromise = @service.localizeType( 282 | path, 283 | @selectedBufferRange.end.row + 1, 284 | fqcn 285 | ) 286 | 287 | typeResolutionPromises.push typeResolutionPromise.then( 288 | localizeTypeSuccessHandler, 289 | localizeTypeFailureHandler 290 | ) 291 | 292 | else 293 | typeResolutionPromises.push Promise.resolve(fqcn) 294 | 295 | combineResolvedTypesHandler = (processedTypeArray) -> 296 | parameter.types = processedTypeArray 297 | 298 | return parameter 299 | 300 | return Promise.all(typeResolutionPromises).then( 301 | combineResolvedTypesHandler, 302 | combineResolvedTypesHandler 303 | ) 304 | 305 | failureHandler = () => 306 | return null 307 | 308 | return @service.deduceTypesAt(parameter.name, editor, @selectedBufferRange.end).then( 309 | successHandler, 310 | failureHandler 311 | ) 312 | 313 | ###* 314 | * Returns all the variable declarations that have been parsed. 315 | * 316 | * @return {Array} 317 | ### 318 | getVariableDeclarations: -> 319 | return @variableDeclarations 320 | 321 | ###* 322 | * Clean up any data from previous usage 323 | ### 324 | cleanUp: -> 325 | @variableDeclarations = [] 326 | -------------------------------------------------------------------------------- /lib/ExtractMethodProvider/View.coffee: -------------------------------------------------------------------------------- 1 | {$, TextEditorView, View} = require 'atom-space-pen-views' 2 | 3 | Parser = require('./Builder') 4 | 5 | module.exports = 6 | 7 | class ExtractMethodView extends View 8 | 9 | ###* 10 | * The callback to invoke when the user confirms his selections. 11 | * 12 | * @type {Callback} 13 | ### 14 | onDidConfirm : null 15 | 16 | ###* 17 | * The callback to invoke when the user cancels the view. 18 | * 19 | * @type {Callback} 20 | ### 21 | onDidCancel : null 22 | 23 | ###* 24 | * Settings of how to generate new method that will be passed to the parser 25 | * 26 | * @type {Object} 27 | ### 28 | settings : null 29 | 30 | ###* 31 | * Builder to use when generating preview area 32 | * 33 | * @type {Builder} 34 | ### 35 | builder : null 36 | 37 | ###* 38 | * Constructor. 39 | * 40 | * @param {Callback} onDidConfirm 41 | * @param {Callback} onDidCancel 42 | ### 43 | constructor: (@onDidConfirm, @onDidCancel = null) -> 44 | super() 45 | 46 | @settings = { 47 | generateDocs: true, 48 | methodName: '', 49 | visibility: 'protected', 50 | tabs: false, 51 | arraySyntax: 'brackets', 52 | typeHinting: true, 53 | generateDescPlaceholders: false 54 | } 55 | 56 | ###* 57 | * Content to be displayed when this view is shown. 58 | ### 59 | @content: -> 60 | @div class: 'php-integrator-refactoring-extract-method', => 61 | @div outlet: 'methodNameForm', => 62 | @subview 'methodNameEditor', new TextEditorView(mini:true, placeholderText: 'Enter a method name') 63 | @div class: 'text-error error-message hide error-message--method-name', 'You must enter a method name!' 64 | @div class: 'settings-view', => 65 | @div class: 'section-body', => 66 | @div class: 'control-group', => 67 | @div class: 'controls', => 68 | @label class: 'control-label', => 69 | @div class: 'setting-title', 'Access Modifier' 70 | @select outlet: 'accessMethodsInput', class: 'form-control', => 71 | @option value: 'public', 'Public' 72 | @option value: 'protected', selected: "selected", 'Protected' 73 | @option value: 'private', 'Private' 74 | @div class: 'control-group', => 75 | @label class: 'control-label', => 76 | @div class: 'setting-title', 'Documentation' 77 | @div class: 'controls', => 78 | @div class: 'checkbox', => 79 | @label => 80 | @input outlet: 'generateDocInput', type: 'checkbox', checked: true 81 | @div class: 'setting-title', 'Generate documentation' 82 | @div class: 'controls generate-docs-control', => 83 | @div class: 'checkbox', => 84 | @label => 85 | @input outlet: 'generateDescPlaceholdersInput', type: 'checkbox' 86 | @div class: 'setting-title', 'Generate description placeholders' 87 | @div class: 'control-group', => 88 | @label class: 'control-label', => 89 | @div class: 'setting-title', 'Type hinting' 90 | @div class: 'controls', => 91 | @div class: 'checkbox', => 92 | @label => 93 | @input outlet: 'generateTypeHints', type: 'checkbox', checked: true 94 | @div class: 'setting-title', 'Generate type hints' 95 | @div class: 'return-multiple-control control-group', => 96 | @label class: 'control-label', => 97 | @div class: 'setting-title', 'Method styling' 98 | @div class: 'controls', => 99 | @div class: 'checkbox', => 100 | @label => 101 | @input outlet: 'arraySyntax', type: 'checkbox', checked: true 102 | @div class: 'setting-title', 'Use PHP 5.4 array syntax (square brackets)' 103 | @div class: 'control-group', => 104 | @div class: 'controls', => 105 | @label class: 'control-label', => 106 | @div class: 'setting-title', 'Preview' 107 | @div class: 'preview-area', => 108 | @subview 'previewArea', new TextEditorView(), class: 'preview-area' 109 | @div class: 'button-bar', => 110 | @button class: 'btn btn-error inline-block-tight pull-left icon icon-circle-slash button--cancel', 'Cancel' 111 | @button class: 'btn btn-success inline-block-tight pull-right icon icon-gear button--confirm', 'Extract' 112 | @div class: 'clear-float' 113 | 114 | ###* 115 | * @inheritdoc 116 | ### 117 | initialize: -> 118 | atom.commands.add @element, 119 | 'core:confirm': (event) => 120 | @confirm() 121 | event.stopPropagation() 122 | 'core:cancel': (event) => 123 | @cancel() 124 | event.stopPropagation() 125 | 126 | @on 'click', 'button', (event) => 127 | @confirm() if $(event.target).hasClass('button--confirm') 128 | @cancel() if $(event.target).hasClass('button--cancel') 129 | 130 | @methodNameEditor.getModel().onDidChange () => 131 | @settings.methodName = @methodNameEditor.getText() 132 | $('.php-integrator-refactoring-extract-method .error-message--method-name').addClass('hide'); 133 | 134 | @refreshPreviewArea() 135 | 136 | $(@accessMethodsInput[0]).change (event) => 137 | @settings.visibility = $(event.target).val() 138 | @refreshPreviewArea() 139 | 140 | $(@generateDocInput[0]).change (event) => 141 | @settings.generateDocs = !@settings.generateDocs 142 | if @settings.generateDocs == true 143 | $('.php-integrator-refactoring-extract-method .generate-docs-control').removeClass('hide') 144 | else 145 | $('.php-integrator-refactoring-extract-method .generate-docs-control').addClass('hide') 146 | 147 | 148 | @refreshPreviewArea() 149 | 150 | $(@generateDescPlaceholdersInput[0]).change (event) => 151 | @settings.generateDescPlaceholders = !@settings.generateDescPlaceholders 152 | @refreshPreviewArea() 153 | 154 | $(@generateTypeHints[0]).change (event) => 155 | @settings.typeHinting = !@settings.typeHinting 156 | @refreshPreviewArea() 157 | 158 | $(@arraySyntax[0]).change (event) => 159 | if @settings.arraySyntax == 'word' 160 | @settings.arraySyntax = 'brackets' 161 | else 162 | @settings.arraySyntax = 'word' 163 | @refreshPreviewArea() 164 | 165 | @panel ?= atom.workspace.addModalPanel(item: this, visible: false) 166 | 167 | previewAreaTextEditor = @previewArea.getModel() 168 | previewAreaTextEditor.setGrammar(atom.grammars.grammarForScopeName('text.html.php')) 169 | 170 | @on 'click', document, (event) => 171 | event.stopPropagation() 172 | 173 | $(document).on 'click', (event) => 174 | @cancel() if @panel?.isVisible() 175 | 176 | ###* 177 | * Destroys the view and cleans up. 178 | ### 179 | destroy: -> 180 | @panel.destroy() 181 | @panel = null 182 | 183 | ###* 184 | * Shows the view and refreshes the preview area with the current settings. 185 | ### 186 | present: -> 187 | @panel.show() 188 | @methodNameEditor.focus() 189 | @methodNameEditor.setText('') 190 | 191 | ###* 192 | * Hides the panel. 193 | ### 194 | hide: -> 195 | @panel?.hide() 196 | @restoreFocus() 197 | 198 | ###* 199 | * Called when the user confirms the extraction and will then call 200 | * onDidConfirm, if set. 201 | ### 202 | confirm: -> 203 | if @settings.methodName == '' 204 | $('.php-integrator-refactoring-extract-method .error-message--method-name').removeClass('hide'); 205 | return false 206 | 207 | if @onDidConfirm 208 | @onDidConfirm(@getSettings()) 209 | 210 | @hide() 211 | 212 | ###* 213 | * Called when the user cancels the extraction and will then call 214 | * onDidCancel, if set. 215 | ### 216 | cancel: -> 217 | if @onDidCancel 218 | @onDidCancel() 219 | 220 | @hide() 221 | 222 | ###* 223 | * Updates the preview area using the current setttings. 224 | ### 225 | refreshPreviewArea: -> 226 | return unless @panel.isVisible() 227 | 228 | successHandler = (methodBody) => 229 | if @builder.hasReturnValues() 230 | if @builder.hasMultipleReturnValues() 231 | $('.php-integrator-refactoring-extract-method .return-multiple-control').removeClass('hide') 232 | else 233 | $('.php-integrator-refactoring-extract-method .return-multiple-control').addClass('hide') 234 | 235 | $('.php-integrator-refactoring-extract-method .return-control').removeClass('hide') 236 | else 237 | $('.php-integrator-refactoring-extract-method .return-control').addClass('hide') 238 | $('.php-integrator-refactoring-extract-method .return-multiple-control').addClass('hide') 239 | 240 | @previewArea.getModel().getBuffer().setText(' 243 | # Do nothing. 244 | 245 | @builder.buildMethod(@getSettings()).then(successHandler, failureHandler) 246 | 247 | ###* 248 | * Stores the currently focused element so it can be returned focus after 249 | * this panel is hidden. 250 | ### 251 | storeFocusedElement: -> 252 | @previouslyFocusedElement = $(document.activeElement) 253 | 254 | ###* 255 | * Restores focus back to the element that was focused before this panel 256 | * was shown. 257 | ### 258 | restoreFocus: -> 259 | @previouslyFocusedElement?.focus() 260 | 261 | ###* 262 | * Sets the builder to use when generating the preview area. 263 | * 264 | * @param {Builder} builder 265 | ### 266 | setBuilder: (builder) -> 267 | @builder = builder 268 | 269 | ###* 270 | * Gets the settings currently set 271 | * 272 | * @return {Object} 273 | ### 274 | getSettings: -> 275 | return @settings 276 | -------------------------------------------------------------------------------- /lib/GetterSetterProvider.coffee: -------------------------------------------------------------------------------- 1 | AbstractProvider = require './AbstractProvider' 2 | 3 | module.exports = 4 | 5 | ##* 6 | # Provides getter and setter (accessor and mutator) generation capabilities. 7 | ## 8 | class GetterSetterProvider extends AbstractProvider 9 | ###* 10 | * The view that allows the user to select the properties to generate for. 11 | ### 12 | selectionView: null 13 | 14 | ###* 15 | * Aids in building methods. 16 | ### 17 | functionBuilder: null 18 | 19 | ###* 20 | * The docblock builder. 21 | ### 22 | docblockBuilder: null 23 | 24 | ###* 25 | * The type helper. 26 | ### 27 | typeHelper: null 28 | 29 | ###* 30 | * @param {Object} typeHelper 31 | * @param {Object} functionBuilder 32 | * @param {Object} docblockBuilder 33 | ### 34 | constructor: (@typeHelper, @functionBuilder, @docblockBuilder) -> 35 | 36 | ###* 37 | * @inheritdoc 38 | ### 39 | activate: (service) -> 40 | super(service) 41 | 42 | atom.commands.add 'atom-workspace', "php-integrator-refactoring:generate-getter": => 43 | @executeCommand(true, false) 44 | 45 | atom.commands.add 'atom-workspace', "php-integrator-refactoring:generate-setter": => 46 | @executeCommand(false, true) 47 | 48 | atom.commands.add 'atom-workspace', "php-integrator-refactoring:generate-getter-setter-pair": => 49 | @executeCommand(true, true) 50 | 51 | ###* 52 | * @inheritdoc 53 | ### 54 | deactivate: () -> 55 | super() 56 | 57 | if @selectionView 58 | @selectionView.destroy() 59 | @selectionView = null 60 | 61 | ###* 62 | * @inheritdoc 63 | ### 64 | getIntentionProviders: () -> 65 | return [{ 66 | grammarScopes: ['source.php'] 67 | getIntentions: ({textEditor, bufferPosition}) => 68 | successHandler = (currentClassName) => 69 | return [] if not currentClassName 70 | 71 | return [ 72 | { 73 | priority : 100 74 | icon : 'gear' 75 | title : 'Generate Getter And Setter Pair(s)' 76 | 77 | selected : () => 78 | @executeCommand(true, true) 79 | } 80 | 81 | { 82 | priority : 100 83 | icon : 'gear' 84 | title : 'Generate Getter(s)' 85 | 86 | selected : () => 87 | @executeCommand(true, false) 88 | }, 89 | 90 | { 91 | priority : 100 92 | icon : 'gear' 93 | title : 'Generate Setter(s)' 94 | 95 | selected : () => 96 | @executeCommand(false, true) 97 | } 98 | ] 99 | 100 | failureHandler = () -> 101 | return [] 102 | 103 | activeTextEditor = atom.workspace.getActiveTextEditor() 104 | 105 | return [] if not activeTextEditor 106 | return [] if not @getCurrentProjectPhpVersion()? 107 | 108 | return @service.determineCurrentClassName(activeTextEditor, activeTextEditor.getCursorBufferPosition()).then(successHandler, failureHandler) 109 | }] 110 | 111 | ###* 112 | * Executes the generation. 113 | * 114 | * @param {boolean} enableGetterGeneration 115 | * @param {boolean} enableSetterGeneration 116 | ### 117 | executeCommand: (enableGetterGeneration, enableSetterGeneration) -> 118 | activeTextEditor = atom.workspace.getActiveTextEditor() 119 | 120 | return if not activeTextEditor 121 | 122 | @getSelectionView().setMetadata({editor: activeTextEditor}) 123 | @getSelectionView().storeFocusedElement() 124 | @getSelectionView().present() 125 | 126 | successHandler = (currentClassName) => 127 | return if not currentClassName 128 | 129 | nestedSuccessHandler = (classInfo) => 130 | enabledItems = [] 131 | disabledItems = [] 132 | 133 | indentationLevel = activeTextEditor.indentationForBufferRow(activeTextEditor.getCursorBufferPosition().row) 134 | 135 | for name, property of classInfo.properties 136 | getterName = 'get' + name.substr(0, 1).toUpperCase() + name.substr(1) 137 | setterName = 'set' + name.substr(0, 1).toUpperCase() + name.substr(1) 138 | 139 | getterExists = if getterName of classInfo.methods then true else false 140 | setterExists = if setterName of classInfo.methods then true else false 141 | 142 | data = { 143 | name : name 144 | types : property.types 145 | needsGetter : enableGetterGeneration 146 | needsSetter : enableSetterGeneration 147 | getterName : getterName 148 | setterName : setterName 149 | tabText : activeTextEditor.getTabText() 150 | indentationLevel : indentationLevel 151 | maxLineLength : atom.config.get('editor.preferredLineLength', activeTextEditor.getLastCursor().getScopeDescriptor()) 152 | } 153 | 154 | if (enableGetterGeneration and enableSetterGeneration and getterExists and setterExists) or 155 | (enableGetterGeneration and getterExists) or 156 | (enableSetterGeneration and setterExists) 157 | data.className = 'php-integrator-refactoring-strikethrough' 158 | disabledItems.push(data) 159 | 160 | else 161 | data.className = '' 162 | enabledItems.push(data) 163 | 164 | @getSelectionView().setItems(enabledItems.concat(disabledItems)) 165 | 166 | nestedFailureHandler = () => 167 | @getSelectionView().setItems([]) 168 | 169 | @service.getClassInfo(currentClassName).then(nestedSuccessHandler, nestedFailureHandler) 170 | 171 | failureHandler = () => 172 | @getSelectionView().setItems([]) 173 | 174 | @service.determineCurrentClassName(activeTextEditor, activeTextEditor.getCursorBufferPosition()).then(successHandler, failureHandler) 175 | 176 | ###* 177 | * Indicates if the specified type is a class type or not. 178 | * 179 | * @return {bool} 180 | ### 181 | isClassType: (type) -> 182 | return if type.substr(0, 1).toUpperCase() == type.substr(0, 1) then true else false 183 | 184 | ###* 185 | * Called when the selection of properties is cancelled. 186 | * 187 | * @param {Object|null} metadata 188 | ### 189 | onCancel: (metadata) -> 190 | 191 | ###* 192 | * Called when the selection of properties is confirmed. 193 | * 194 | * @param {array} selectedItems 195 | * @param {Object|null} metadata 196 | ### 197 | onConfirm: (selectedItems, metadata) -> 198 | itemOutputs = [] 199 | 200 | for item in selectedItems 201 | if item.needsGetter 202 | itemOutputs.push(@generateGetterForItem(item)) 203 | 204 | if item.needsSetter 205 | itemOutputs.push(@generateSetterForItem(item)) 206 | 207 | output = itemOutputs.join("\n").trim() 208 | 209 | metadata.editor.getBuffer().insert(metadata.editor.getCursorBufferPosition(), output) 210 | 211 | ###* 212 | * Generates a getter for the specified selected item. 213 | * 214 | * @param {Object} item 215 | * 216 | * @return {string} 217 | ### 218 | generateGetterForItem: (item) -> 219 | typeSpecification = @typeHelper.buildTypeSpecificationFromTypeArray(item.types) 220 | 221 | statements = [ 222 | "return $this->#{item.name};" 223 | ] 224 | 225 | functionText = @functionBuilder 226 | .makePublic() 227 | .setIsStatic(false) 228 | .setIsAbstract(false) 229 | .setName(item.getterName) 230 | .setReturnType(@typeHelper.getReturnTypeHintForTypeSpecification(typeSpecification)) 231 | .setParameters([]) 232 | .setStatements(statements) 233 | .setTabText(item.tabText) 234 | .setIndentationLevel(item.indentationLevel) 235 | .setMaxLineLength(item.maxLineLength) 236 | .build() 237 | 238 | docblockText = @docblockBuilder.buildForMethod( 239 | [], 240 | typeSpecification, 241 | false, 242 | item.tabText.repeat(item.indentationLevel) 243 | ) 244 | 245 | return docblockText + functionText 246 | 247 | ###* 248 | * Generates a setter for the specified selected item. 249 | * 250 | * @param {Object} item 251 | * 252 | * @return {string} 253 | ### 254 | generateSetterForItem: (item) -> 255 | typeSpecification = @typeHelper.buildTypeSpecificationFromTypeArray(item.types) 256 | parameterTypeHint = @typeHelper.getTypeHintForTypeSpecification(typeSpecification) 257 | 258 | statements = [ 259 | "$this->#{item.name} = $#{item.name};" 260 | "return $this;" 261 | ] 262 | 263 | parameters = [ 264 | { 265 | name : '$' + item.name 266 | typeHint : parameterTypeHint.typeHint 267 | defaultValue : if parameterTypeHint.shouldSetDefaultValueToNull then 'null' else null 268 | } 269 | ] 270 | 271 | functionText = @functionBuilder 272 | .makePublic() 273 | .setIsStatic(false) 274 | .setIsAbstract(false) 275 | .setName(item.setterName) 276 | .setReturnType(null) 277 | .setParameters(parameters) 278 | .setStatements(statements) 279 | .setTabText(item.tabText) 280 | .setIndentationLevel(item.indentationLevel) 281 | .setMaxLineLength(item.maxLineLength) 282 | .build() 283 | 284 | docblockText = @docblockBuilder.buildForMethod( 285 | [{name : '$' + item.name, type : typeSpecification}], 286 | 'static', 287 | false, 288 | item.tabText.repeat(item.indentationLevel) 289 | ) 290 | 291 | return docblockText + functionText 292 | 293 | ###* 294 | * @return {Builder} 295 | ### 296 | getSelectionView: () -> 297 | if not @selectionView? 298 | View = require './GetterSetterProvider/View' 299 | 300 | @selectionView = new View(@onConfirm.bind(this), @onCancel.bind(this)) 301 | @selectionView.setLoading('Loading class information...') 302 | @selectionView.setEmptyMessage('No properties found.') 303 | 304 | return @selectionView 305 | -------------------------------------------------------------------------------- /lib/GetterSetterProvider/View.coffee: -------------------------------------------------------------------------------- 1 | {$, $$, SelectListView} = require 'atom-space-pen-views' 2 | 3 | MultiSelectionView = require '../Utility/MultiSelectionView.coffee' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # An extension on SelectListView from atom-space-pen-views that allows multiple selections. 9 | ## 10 | class View extends MultiSelectionView 11 | ###* 12 | * @inheritdoc 13 | ### 14 | createWidgets: () -> 15 | checkboxBar = $$ -> 16 | @div class: 'checkbox-bar settings-view', => 17 | @div class: 'controls', => 18 | @div class: 'block text-line', => 19 | @label class: 'icon icon-info', 'Tip: The order in which items are selected determines the order of the output.' 20 | 21 | checkboxBar.appendTo(this) 22 | 23 | # Ensure that button clicks are actually handled. 24 | @on 'mousedown', ({target}) => 25 | return false if $(target).hasClass('checkbox-input') 26 | return false if $(target).hasClass('checkbox-label-text') 27 | 28 | super() 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | invokeOnDidConfirm: () -> 34 | if @onDidConfirm 35 | @onDidConfirm(@selectedItems, @getMetadata()) 36 | -------------------------------------------------------------------------------- /lib/IntroducePropertyProvider.coffee: -------------------------------------------------------------------------------- 1 | {Point} = require 'atom' 2 | 3 | AbstractProvider = require './AbstractProvider' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # Provides property generation for non-existent properties. 9 | ## 10 | class IntroducePropertyProvider extends AbstractProvider 11 | ###* 12 | * The docblock builder. 13 | ### 14 | docblockBuilder: null 15 | 16 | ###* 17 | * @param {Object} docblockBuilder 18 | ### 19 | constructor: (@docblockBuilder) -> 20 | 21 | ###* 22 | * @inheritdoc 23 | ### 24 | getIntentionProviders: () -> 25 | return [{ 26 | grammarScopes: ['variable.other.property.php'] 27 | getIntentions: ({textEditor, bufferPosition}) => 28 | nameRange = textEditor.bufferRangeForScopeAtCursor('variable.other.property') 29 | 30 | return if not nameRange? 31 | return [] if not @getCurrentProjectPhpVersion()? 32 | 33 | name = textEditor.getTextInBufferRange(nameRange) 34 | 35 | return @getIntentions(textEditor, bufferPosition, name) 36 | }] 37 | 38 | ###* 39 | * @param {TextEditor} editor 40 | * @param {Point} triggerPosition 41 | * @param {String} name 42 | ### 43 | getIntentions: (editor, triggerPosition, name) -> 44 | failureHandler = () => 45 | return [] 46 | 47 | successHandler = (currentClassName) => 48 | return [] if not currentClassName? 49 | 50 | nestedSuccessHandler = (classInfo) => 51 | intentions = [] 52 | 53 | return intentions if not classInfo 54 | 55 | if name not of classInfo.properties 56 | intentions.push({ 57 | priority : 100 58 | icon : 'gear' 59 | title : 'Introduce New Property' 60 | 61 | selected : () => 62 | @introducePropertyFor(editor, classInfo, name) 63 | }) 64 | 65 | return intentions 66 | 67 | @service.getClassInfo(currentClassName).then(nestedSuccessHandler, failureHandler) 68 | 69 | @service.determineCurrentClassName(editor, triggerPosition).then(successHandler, failureHandler) 70 | 71 | ###* 72 | * @param {TextEditor} editor 73 | * @param {Object} classData 74 | * @param {String} name 75 | ### 76 | introducePropertyFor: (editor, classData, name) -> 77 | indentationLevel = editor.indentationForBufferRow(classData.startLine - 1) + 1 78 | 79 | tabText = editor.getTabText().repeat(indentationLevel) 80 | 81 | docblock = @docblockBuilder.buildForProperty( 82 | 'mixed', 83 | false, 84 | tabText 85 | ) 86 | 87 | property = "#{tabText}protected $#{name};\n\n" 88 | 89 | point = @findLocationToInsertProperty(editor, classData) 90 | 91 | editor.getBuffer().insert(point, docblock + property) 92 | 93 | 94 | ###* 95 | * @param {TextEditor} editor 96 | * @param {Object} classData 97 | * 98 | * @return {Point} 99 | ### 100 | findLocationToInsertProperty: (editor, classData) -> 101 | startLine = null 102 | 103 | # Try to place the new property underneath the existing properties. 104 | for name,propertyData of classData.properties 105 | if propertyData.declaringStructure.name == classData.name 106 | startLine = propertyData.endLine + 1 107 | 108 | if not startLine? 109 | # Ensure we don't end up somewhere in the middle of the class definition if it spans multiple lines. 110 | lineCount = editor.getLineCount() 111 | 112 | for line in [classData.startLine .. lineCount] 113 | lineText = editor.lineTextForBufferRow(line) 114 | 115 | continue if not lineText? 116 | 117 | for i in [0 .. lineText.length - 1] 118 | if lineText[i] == '{' 119 | startLine = line + 1 120 | break 121 | 122 | break if startLine? 123 | 124 | if not startLine? 125 | startLine = classData.startLine + 1 126 | 127 | return new Point(startLine, -1) 128 | -------------------------------------------------------------------------------- /lib/Main.coffee: -------------------------------------------------------------------------------- 1 | module.exports = 2 | ###* 3 | * The name of the package. 4 | * 5 | * @var {String} 6 | ### 7 | packageName: 'php-integrator-refactoring' 8 | 9 | ###* 10 | * List of refactoring providers. 11 | * 12 | * @var {Array} 13 | ### 14 | providers: [] 15 | 16 | ###* 17 | * @var {Object|null} 18 | ### 19 | typeHelper: null 20 | 21 | ###* 22 | * @var {Object|null} 23 | ### 24 | docblockBuilder: null 25 | 26 | ###* 27 | * @var {Object|null} 28 | ### 29 | functionBuilder: null 30 | 31 | ###* 32 | * @var {Object|null} 33 | ### 34 | parameterParser: null 35 | 36 | ###* 37 | * @var {Object|null} 38 | ### 39 | builder: null 40 | 41 | ###* 42 | * Activates the package. 43 | ### 44 | activate: -> 45 | DocblockProvider = require './DocblockProvider' 46 | GetterSetterProvider = require './GetterSetterProvider' 47 | ExtractMethodProvider = require './ExtractMethodProvider' 48 | OverrideMethodProvider = require './OverrideMethodProvider' 49 | IntroducePropertyProvider = require './IntroducePropertyProvider' 50 | StubAbstractMethodProvider = require './StubAbstractMethodProvider' 51 | StubInterfaceMethodProvider = require './StubInterfaceMethodProvider' 52 | ConstructorGenerationProvider = require './ConstructorGenerationProvider' 53 | 54 | @providers = [] 55 | @providers.push new DocblockProvider(@getTypeHelper(), @getDocblockBuilder()) 56 | @providers.push new IntroducePropertyProvider(@getDocblockBuilder()) 57 | @providers.push new GetterSetterProvider(@getTypeHelper(), @getFunctionBuilder(), @getDocblockBuilder()) 58 | @providers.push new ExtractMethodProvider(@getBuilder()) 59 | @providers.push new ConstructorGenerationProvider(@getTypeHelper(), @getFunctionBuilder(), @getDocblockBuilder()) 60 | 61 | @providers.push new OverrideMethodProvider(@getDocblockBuilder(), @getFunctionBuilder()) 62 | @providers.push new StubAbstractMethodProvider(@getDocblockBuilder(), @getFunctionBuilder()) 63 | @providers.push new StubInterfaceMethodProvider(@getDocblockBuilder(), @getFunctionBuilder()) 64 | 65 | require('atom-package-deps').install(@packageName) 66 | 67 | ###* 68 | * Deactivates the package. 69 | ### 70 | deactivate: -> 71 | @deactivateProviders() 72 | 73 | ###* 74 | * Activates the providers using the specified service. 75 | * 76 | * @param {Object} service 77 | ### 78 | activateProviders: (service) -> 79 | for provider in @providers 80 | provider.activate(service) 81 | 82 | ###* 83 | * Deactivates any active providers. 84 | ### 85 | deactivateProviders: () -> 86 | for provider in @providers 87 | provider.deactivate() 88 | 89 | @providers = [] 90 | 91 | ###* 92 | * Sets the php-integrator service. 93 | * 94 | * @param {Object} service 95 | * 96 | * @return {Disposable} 97 | ### 98 | setService: (service) -> 99 | @activateProviders(service) 100 | @getBuilder().setService(service) 101 | @getTypeHelper().setService(service) 102 | 103 | {Disposable} = require 'atom' 104 | 105 | return new Disposable => @deactivateProviders() 106 | 107 | ###* 108 | * Consumes the atom/snippet service. 109 | * 110 | * @param {Object} snippetManager 111 | ### 112 | setSnippetManager: (snippetManager) -> 113 | for provider in @providers 114 | provider.setSnippetManager snippetManager 115 | 116 | ###* 117 | * Returns a list of intention providers. 118 | * 119 | * @return {Array} 120 | ### 121 | provideIntentions: () -> 122 | intentionProviders = [] 123 | 124 | for provider in @providers 125 | intentionProviders = intentionProviders.concat(provider.getIntentionProviders()) 126 | 127 | return intentionProviders 128 | 129 | ###* 130 | * @return {TypeHelper} 131 | ### 132 | getTypeHelper: () -> 133 | if not @typeHelper? 134 | TypeHelper = require './Utility/TypeHelper' 135 | 136 | @typeHelper = new TypeHelper() 137 | 138 | return @typeHelper 139 | 140 | ###* 141 | * @return {DocblockBuilder} 142 | ### 143 | getDocblockBuilder: () -> 144 | if not @docblockBuilder? 145 | DocblockBuilder = require './Utility/DocblockBuilder' 146 | 147 | @docblockBuilder = new DocblockBuilder() 148 | 149 | return @docblockBuilder 150 | 151 | ###* 152 | * @return {FunctionBuilder} 153 | ### 154 | getFunctionBuilder: () -> 155 | if not @functionBuilder? 156 | FunctionBuilder = require './Utility/FunctionBuilder' 157 | 158 | @functionBuilder = new FunctionBuilder() 159 | 160 | return @functionBuilder 161 | 162 | ###* 163 | * @return {ParameterParser} 164 | ### 165 | getParameterParser: () -> 166 | if not @parameterParser? 167 | ParameterParser = require './ExtractMethodProvider/ParameterParser' 168 | 169 | @parameterParser = new ParameterParser(@getTypeHelper()) 170 | 171 | return @parameterParser 172 | 173 | ###* 174 | * @return {Builder} 175 | ### 176 | getBuilder: () -> 177 | if not @builder? 178 | Builder = require './ExtractMethodProvider/Builder' 179 | 180 | @builder = new Builder( 181 | @getParameterParser(), 182 | @getDocblockBuilder(), 183 | @getFunctionBuilder(), 184 | @getTypeHelper() 185 | ) 186 | 187 | return @builder 188 | -------------------------------------------------------------------------------- /lib/OverrideMethodProvider.coffee: -------------------------------------------------------------------------------- 1 | AbstractProvider = require './AbstractProvider' 2 | 3 | module.exports = 4 | 5 | ##* 6 | # Provides the ability to implement interface methods. 7 | ## 8 | class OverrideMethodProvider extends AbstractProvider 9 | ###* 10 | * The view that allows the user to select the properties to generate for. 11 | ### 12 | selectionView: null 13 | 14 | ###* 15 | * @type {Object} 16 | ### 17 | docblockBuilder: null 18 | 19 | ###* 20 | * @type {Object} 21 | ### 22 | functionBuilder: null 23 | 24 | ###* 25 | * @param {Object} docblockBuilder 26 | * @param {Object} functionBuilder 27 | ### 28 | constructor: (@docblockBuilder, @functionBuilder) -> 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | deactivate: () -> 34 | super() 35 | 36 | if @selectionView 37 | @selectionView.destroy() 38 | @selectionView = null 39 | 40 | ###* 41 | * @inheritdoc 42 | ### 43 | getIntentionProviders: () -> 44 | return [{ 45 | grammarScopes: ['source.php'] 46 | getIntentions: ({textEditor, bufferPosition}) => 47 | return [] if not @getCurrentProjectPhpVersion()? 48 | 49 | return @getStubInterfaceMethodIntentions(textEditor, bufferPosition) 50 | }] 51 | 52 | ###* 53 | * @param {TextEditor} editor 54 | * @param {Point} triggerPosition 55 | ### 56 | getStubInterfaceMethodIntentions: (editor, triggerPosition) -> 57 | failureHandler = () -> 58 | return [] 59 | 60 | successHandler = (currentClassName) => 61 | return [] if not currentClassName 62 | 63 | nestedSuccessHandler = (classInfo) => 64 | return [] if not classInfo 65 | 66 | items = [] 67 | 68 | for name, method of classInfo.methods 69 | data = { 70 | name : name 71 | method : method 72 | } 73 | 74 | # Interface methods can already be stubbed via StubInterfaceMethodProvider. 75 | continue if method.declaringStructure.type == 'interface' 76 | 77 | # Abstract methods can already be stubbed via StubAbstractMethodProvider. 78 | continue if method.isAbstract 79 | 80 | if method.declaringStructure.name != classInfo.name 81 | items.push(data) 82 | 83 | return [] if items.length == 0 84 | 85 | @getSelectionView().setItems(items) 86 | 87 | return [ 88 | { 89 | priority : 100 90 | icon : 'link' 91 | title : 'Override Method(s)' 92 | 93 | selected : () => 94 | @executeStubInterfaceMethods(editor) 95 | } 96 | ] 97 | 98 | return @service.getClassInfo(currentClassName).then(nestedSuccessHandler, failureHandler) 99 | 100 | return @service.determineCurrentClassName(editor, triggerPosition).then(successHandler, failureHandler) 101 | 102 | ###* 103 | * @param {TextEditor} editor 104 | * @param {Point} triggerPosition 105 | ### 106 | executeStubInterfaceMethods: (editor) -> 107 | @getSelectionView().setMetadata({editor: editor}) 108 | @getSelectionView().storeFocusedElement() 109 | @getSelectionView().present() 110 | 111 | ###* 112 | * Called when the selection of properties is cancelled. 113 | ### 114 | onCancel: (metadata) -> 115 | 116 | ###* 117 | * Called when the selection of properties is confirmed. 118 | * 119 | * @param {array} selectedItems 120 | * @param {Object|null} metadata 121 | ### 122 | onConfirm: (selectedItems, metadata) -> 123 | itemOutputs = [] 124 | 125 | tabText = metadata.editor.getTabText() 126 | indentationLevel = metadata.editor.indentationForBufferRow(metadata.editor.getCursorBufferPosition().row) 127 | maxLineLength = atom.config.get('editor.preferredLineLength', metadata.editor.getLastCursor().getScopeDescriptor()) 128 | 129 | for item in selectedItems 130 | stub = @generateStubForInterfaceMethod(item.method, tabText, indentationLevel, maxLineLength) 131 | 132 | itemOutputs.push(stub) 133 | 134 | output = itemOutputs.join("\n").trim() 135 | 136 | metadata.editor.insertText(output) 137 | 138 | ###* 139 | * Generates an override for the specified selected data. 140 | * 141 | * @param {Object} data 142 | * @param {String} tabText 143 | * @param {Number} indentationLevel 144 | * @param {Number} maxLineLength 145 | * 146 | * @return {string} 147 | ### 148 | generateStubForInterfaceMethod: (data, tabText, indentationLevel, maxLineLength) -> 149 | parameterNames = data.parameters.map (item) -> 150 | return '$' + item.name 151 | 152 | hasReturnValue = @hasReturnValue(data) 153 | 154 | parentCallStatement = '' 155 | 156 | if hasReturnValue 157 | parentCallStatement += '$value = ' 158 | 159 | parentCallStatement += 'parent::' + data.name + '(' 160 | parentCallStatement += parameterNames.join(', ') 161 | parentCallStatement += ');' 162 | 163 | statements = [ 164 | parentCallStatement 165 | '' 166 | '// TODO' 167 | ] 168 | 169 | if hasReturnValue 170 | statements.push('') 171 | statements.push('return $value;') 172 | 173 | functionText = @functionBuilder 174 | .setFromRawMethodData(data) 175 | .setIsAbstract(false) 176 | .setStatements(statements) 177 | .setTabText(tabText) 178 | .setIndentationLevel(indentationLevel) 179 | .setMaxLineLength(maxLineLength) 180 | .build() 181 | 182 | docblockText = @docblockBuilder.buildByLines(['@inheritDoc'], tabText.repeat(indentationLevel)) 183 | 184 | return docblockText + functionText 185 | 186 | ###* 187 | * @param {Object} data 188 | * 189 | * @return {Boolean} 190 | ### 191 | hasReturnValue: (data) -> 192 | return false if data.name == '__construct' 193 | return false if data.returnTypes.length == 0 194 | return false if data.returnTypes.length == 1 and data.returnTypes[0].type == 'void' 195 | 196 | return true 197 | 198 | ###* 199 | * @return {Builder} 200 | ### 201 | getSelectionView: () -> 202 | if not @selectionView? 203 | View = require './OverrideMethodProvider/View' 204 | 205 | @selectionView = new View(@onConfirm.bind(this), @onCancel.bind(this)) 206 | @selectionView.setLoading('Loading class information...') 207 | @selectionView.setEmptyMessage('No overridable methods found.') 208 | 209 | return @selectionView 210 | -------------------------------------------------------------------------------- /lib/OverrideMethodProvider/View.coffee: -------------------------------------------------------------------------------- 1 | {$, $$, SelectListView} = require 'atom-space-pen-views' 2 | 3 | MultiSelectionView = require '../Utility/MultiSelectionView.coffee' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # An extension on SelectListView from atom-space-pen-views that allows multiple selections. 9 | ## 10 | class View extends MultiSelectionView 11 | ###* 12 | * @inheritdoc 13 | ### 14 | createWidgets: () -> 15 | checkboxBar = $$ -> 16 | @div class: 'checkbox-bar settings-view', => 17 | @div class: 'controls', => 18 | @div class: 'block text-line', => 19 | @label class: 'icon icon-info', 'Tip: The order in which items are selected determines the order of the output.' 20 | 21 | checkboxBar.appendTo(this) 22 | 23 | # Ensure that button clicks are actually handled. 24 | @on 'mousedown', ({target}) => 25 | return false if $(target).hasClass('checkbox-input') 26 | return false if $(target).hasClass('checkbox-label-text') 27 | 28 | super() 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | invokeOnDidConfirm: () -> 34 | if @onDidConfirm 35 | @onDidConfirm(@selectedItems, @getMetadata()) 36 | -------------------------------------------------------------------------------- /lib/StubAbstractMethodProvider.coffee: -------------------------------------------------------------------------------- 1 | AbstractProvider = require './AbstractProvider' 2 | 3 | module.exports = 4 | 5 | ##* 6 | # Provides the ability to stub abstract methods. 7 | ## 8 | class StubAbstractMethodProvider extends AbstractProvider 9 | ###* 10 | * The view that allows the user to select the properties to generate for. 11 | ### 12 | selectionView: null 13 | 14 | ###* 15 | * @type {Object} 16 | ### 17 | docblockBuilder: null 18 | 19 | ###* 20 | * @type {Object} 21 | ### 22 | functionBuilder: null 23 | 24 | ###* 25 | * @param {Object} docblockBuilder 26 | * @param {Object} functionBuilder 27 | ### 28 | constructor: (@docblockBuilder, @functionBuilder) -> 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | deactivate: () -> 34 | super() 35 | 36 | if @selectionView 37 | @selectionView.destroy() 38 | @selectionView = null 39 | 40 | ###* 41 | * @inheritdoc 42 | ### 43 | getIntentionProviders: () -> 44 | return [{ 45 | grammarScopes: ['source.php'] 46 | getIntentions: ({textEditor, bufferPosition}) => 47 | return [] if not @getCurrentProjectPhpVersion()? 48 | 49 | return @getStubInterfaceMethodIntentions(textEditor, bufferPosition) 50 | }] 51 | 52 | ###* 53 | * @param {TextEditor} editor 54 | * @param {Point} triggerPosition 55 | ### 56 | getStubInterfaceMethodIntentions: (editor, triggerPosition) -> 57 | failureHandler = () -> 58 | return [] 59 | 60 | successHandler = (currentClassName) => 61 | return [] if not currentClassName 62 | 63 | nestedSuccessHandler = (classInfo) => 64 | return [] if not classInfo 65 | 66 | items = [] 67 | 68 | for name, method of classInfo.methods 69 | data = { 70 | name : name 71 | method : method 72 | } 73 | 74 | if method.isAbstract 75 | items.push(data) 76 | 77 | return [] if items.length == 0 78 | 79 | @getSelectionView().setItems(items) 80 | 81 | return [ 82 | { 83 | priority : 100 84 | icon : 'link' 85 | title : 'Stub Unimplemented Abstract Method(s)' 86 | 87 | selected : () => 88 | @executeStubInterfaceMethods(editor) 89 | } 90 | ] 91 | 92 | return @service.getClassInfo(currentClassName).then(nestedSuccessHandler, failureHandler) 93 | 94 | return @service.determineCurrentClassName(editor, triggerPosition).then(successHandler, failureHandler) 95 | 96 | ###* 97 | * @param {TextEditor} editor 98 | * @param {Point} triggerPosition 99 | ### 100 | executeStubInterfaceMethods: (editor) -> 101 | @getSelectionView().setMetadata({editor: editor}) 102 | @getSelectionView().storeFocusedElement() 103 | @getSelectionView().present() 104 | 105 | ###* 106 | * Called when the selection of properties is cancelled. 107 | ### 108 | onCancel: (metadata) -> 109 | 110 | ###* 111 | * Called when the selection of properties is confirmed. 112 | * 113 | * @param {array} selectedItems 114 | * @param {Object|null} metadata 115 | ### 116 | onConfirm: (selectedItems, metadata) -> 117 | itemOutputs = [] 118 | 119 | tabText = metadata.editor.getTabText() 120 | indentationLevel = metadata.editor.indentationForBufferRow(metadata.editor.getCursorBufferPosition().row) 121 | maxLineLength = atom.config.get('editor.preferredLineLength', metadata.editor.getLastCursor().getScopeDescriptor()) 122 | 123 | for item in selectedItems 124 | itemOutputs.push(@generateStubForInterfaceMethod(item.method, tabText, indentationLevel, maxLineLength)) 125 | 126 | output = itemOutputs.join("\n").trim() 127 | 128 | metadata.editor.insertText(output) 129 | 130 | ###* 131 | * Generates a stub for the specified selected data. 132 | * 133 | * @param {Object} data 134 | * @param {String} tabText 135 | * @param {Number} indentationLevel 136 | * @param {Number} maxLineLength 137 | * 138 | * @return {string} 139 | ### 140 | generateStubForInterfaceMethod: (data, tabText, indentationLevel, maxLineLength) -> 141 | statements = [ 142 | "throw new \\LogicException('Not implemented'); // TODO" 143 | ] 144 | 145 | functionText = @functionBuilder 146 | .setFromRawMethodData(data) 147 | .setIsAbstract(false) 148 | .setStatements(statements) 149 | .setTabText(tabText) 150 | .setIndentationLevel(indentationLevel) 151 | .setMaxLineLength(maxLineLength) 152 | .build() 153 | 154 | docblockText = @docblockBuilder.buildByLines(['@inheritDoc'], tabText.repeat(indentationLevel)) 155 | 156 | return docblockText + functionText 157 | 158 | ###* 159 | * @return {Builder} 160 | ### 161 | getSelectionView: () -> 162 | if not @selectionView? 163 | View = require './StubAbstractMethodProvider/View' 164 | 165 | @selectionView = new View(@onConfirm.bind(this), @onCancel.bind(this)) 166 | @selectionView.setLoading('Loading class information...') 167 | @selectionView.setEmptyMessage('No unimplemented abstract methods found.') 168 | 169 | return @selectionView 170 | -------------------------------------------------------------------------------- /lib/StubAbstractMethodProvider/View.coffee: -------------------------------------------------------------------------------- 1 | {$, $$, SelectListView} = require 'atom-space-pen-views' 2 | 3 | MultiSelectionView = require '../Utility/MultiSelectionView.coffee' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # An extension on SelectListView from atom-space-pen-views that allows multiple selections. 9 | ## 10 | class View extends MultiSelectionView 11 | ###* 12 | * @inheritdoc 13 | ### 14 | createWidgets: () -> 15 | checkboxBar = $$ -> 16 | @div class: 'checkbox-bar settings-view', => 17 | @div class: 'controls', => 18 | @div class: 'block text-line', => 19 | @label class: 'icon icon-info', 'Tip: The order in which items are selected determines the order of the output.' 20 | 21 | checkboxBar.appendTo(this) 22 | 23 | # Ensure that button clicks are actually handled. 24 | @on 'mousedown', ({target}) => 25 | return false if $(target).hasClass('checkbox-input') 26 | return false if $(target).hasClass('checkbox-label-text') 27 | 28 | super() 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | invokeOnDidConfirm: () -> 34 | if @onDidConfirm 35 | @onDidConfirm(@selectedItems, @getMetadata()) 36 | -------------------------------------------------------------------------------- /lib/StubInterfaceMethodProvider.coffee: -------------------------------------------------------------------------------- 1 | AbstractProvider = require './AbstractProvider' 2 | 3 | module.exports = 4 | 5 | ##* 6 | # Provides the ability to stub interface methods. 7 | ## 8 | class StubInterfaceMethodProvider extends AbstractProvider 9 | ###* 10 | * The view that allows the user to select the properties to generate for. 11 | ### 12 | selectionView: null 13 | 14 | ###* 15 | * @type {Object} 16 | ### 17 | docblockBuilder: null 18 | 19 | ###* 20 | * @type {Object} 21 | ### 22 | functionBuilder: null 23 | 24 | ###* 25 | * @param {Object} docblockBuilder 26 | * @param {Object} functionBuilder 27 | ### 28 | constructor: (@docblockBuilder, @functionBuilder) -> 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | deactivate: () -> 34 | super() 35 | 36 | if @selectionView 37 | @selectionView.destroy() 38 | @selectionView = null 39 | 40 | ###* 41 | * @inheritdoc 42 | ### 43 | getIntentionProviders: () -> 44 | return [{ 45 | grammarScopes: ['source.php'] 46 | getIntentions: ({textEditor, bufferPosition}) => 47 | return [] if not @getCurrentProjectPhpVersion()? 48 | 49 | return @getStubInterfaceMethodIntentions(textEditor, bufferPosition) 50 | }] 51 | 52 | ###* 53 | * @param {TextEditor} editor 54 | * @param {Point} triggerPosition 55 | ### 56 | getStubInterfaceMethodIntentions: (editor, triggerPosition) -> 57 | failureHandler = () -> 58 | return [] 59 | 60 | successHandler = (currentClassName) => 61 | return [] if not currentClassName 62 | 63 | nestedSuccessHandler = (classInfo) => 64 | return [] if not classInfo 65 | 66 | items = [] 67 | 68 | for name, method of classInfo.methods 69 | data = { 70 | name : name 71 | method : method 72 | } 73 | 74 | if method.declaringStructure.type == 'interface' and method.implementations?.length == 0 75 | items.push(data) 76 | 77 | return [] if items.length == 0 78 | 79 | @getSelectionView().setItems(items) 80 | 81 | return [ 82 | { 83 | priority : 100 84 | icon : 'link' 85 | title : 'Stub Unimplemented Interface Method(s)' 86 | 87 | selected : () => 88 | @executeStubInterfaceMethods(editor) 89 | } 90 | ] 91 | 92 | return @service.getClassInfo(currentClassName).then(nestedSuccessHandler, failureHandler) 93 | 94 | return @service.determineCurrentClassName(editor, triggerPosition).then(successHandler, failureHandler) 95 | 96 | ###* 97 | * @param {TextEditor} editor 98 | * @param {Point} triggerPosition 99 | ### 100 | executeStubInterfaceMethods: (editor) -> 101 | @getSelectionView().setMetadata({editor: editor}) 102 | @getSelectionView().storeFocusedElement() 103 | @getSelectionView().present() 104 | 105 | ###* 106 | * Called when the selection of properties is cancelled. 107 | ### 108 | onCancel: (metadata) -> 109 | 110 | ###* 111 | * Called when the selection of properties is confirmed. 112 | * 113 | * @param {array} selectedItems 114 | * @param {Object|null} metadata 115 | ### 116 | onConfirm: (selectedItems, metadata) -> 117 | itemOutputs = [] 118 | 119 | tabText = metadata.editor.getTabText() 120 | indentationLevel = metadata.editor.indentationForBufferRow(metadata.editor.getCursorBufferPosition().row) 121 | maxLineLength = atom.config.get('editor.preferredLineLength', metadata.editor.getLastCursor().getScopeDescriptor()) 122 | 123 | for item in selectedItems 124 | itemOutputs.push(@generateStubForInterfaceMethod(item.method, tabText, indentationLevel, maxLineLength)) 125 | 126 | output = itemOutputs.join("\n").trim() 127 | 128 | metadata.editor.insertText(output) 129 | 130 | ###* 131 | * Generates a stub for the specified selected data. 132 | * 133 | * @param {Object} data 134 | * @param {String} tabText 135 | * @param {Number} indentationLevel 136 | * @param {Number} maxLineLength 137 | * 138 | * @return {string} 139 | ### 140 | generateStubForInterfaceMethod: (data, tabText, indentationLevel, maxLineLength) -> 141 | statements = [ 142 | "throw new \\LogicException('Not implemented'); // TODO" 143 | ] 144 | 145 | functionText = @functionBuilder 146 | .setFromRawMethodData(data) 147 | .setStatements(statements) 148 | .setTabText(tabText) 149 | .setIndentationLevel(indentationLevel) 150 | .setMaxLineLength(maxLineLength) 151 | .build() 152 | 153 | docblockText = @docblockBuilder.buildByLines(['@inheritDoc'], tabText.repeat(indentationLevel)) 154 | 155 | return docblockText + functionText 156 | 157 | ###* 158 | * @return {Builder} 159 | ### 160 | getSelectionView: () -> 161 | if not @selectionView? 162 | View = require './StubInterfaceMethodProvider/View' 163 | 164 | @selectionView = new View(@onConfirm.bind(this), @onCancel.bind(this)) 165 | @selectionView.setLoading('Loading class information...') 166 | @selectionView.setEmptyMessage('No unimplemented interface methods found.') 167 | 168 | return @selectionView 169 | -------------------------------------------------------------------------------- /lib/StubInterfaceMethodProvider/View.coffee: -------------------------------------------------------------------------------- 1 | {$, $$, SelectListView} = require 'atom-space-pen-views' 2 | 3 | MultiSelectionView = require '../Utility/MultiSelectionView.coffee' 4 | 5 | module.exports = 6 | 7 | ##* 8 | # An extension on SelectListView from atom-space-pen-views that allows multiple selections. 9 | ## 10 | class View extends MultiSelectionView 11 | ###* 12 | * @inheritdoc 13 | ### 14 | createWidgets: () -> 15 | checkboxBar = $$ -> 16 | @div class: 'checkbox-bar settings-view', => 17 | @div class: 'controls', => 18 | @div class: 'block text-line', => 19 | @label class: 'icon icon-info', 'Tip: The order in which items are selected determines the order of the output.' 20 | 21 | checkboxBar.appendTo(this) 22 | 23 | # Ensure that button clicks are actually handled. 24 | @on 'mousedown', ({target}) => 25 | return false if $(target).hasClass('checkbox-input') 26 | return false if $(target).hasClass('checkbox-label-text') 27 | 28 | super() 29 | 30 | ###* 31 | * @inheritdoc 32 | ### 33 | invokeOnDidConfirm: () -> 34 | if @onDidConfirm 35 | @onDidConfirm(@selectedItems, @getMetadata()) 36 | -------------------------------------------------------------------------------- /lib/Utility/DocblockBuilder.coffee: -------------------------------------------------------------------------------- 1 | module.exports = 2 | 3 | class DocblockBuilder 4 | ###* 5 | * @param {Array} parameters 6 | * @param {String|null} returnType 7 | * @param {boolean} generateDescriptionPlaceholders 8 | * @param {String} tabText 9 | * 10 | * @return {String} 11 | ### 12 | buildForMethod: (parameters, returnType, generateDescriptionPlaceholders = true, tabText = '') => 13 | lines = [] 14 | 15 | if generateDescriptionPlaceholders 16 | lines.push("[Short description of the method]") 17 | 18 | if parameters.length > 0 19 | descriptionPlaceholder = "" 20 | 21 | if generateDescriptionPlaceholders 22 | lines.push('') 23 | 24 | descriptionPlaceholder = " [Description]" 25 | 26 | # Determine the necessary padding. 27 | parameterTypeLengths = parameters.map (item) -> 28 | return if item.type then item.type.length else 0 29 | 30 | parameterNameLengths = parameters.map (item) -> 31 | return if item.name then item.name.length else 0 32 | 33 | longestTypeLength = Math.max(parameterTypeLengths...) 34 | longestNameLength = Math.max(parameterNameLengths...) 35 | 36 | # Generate parameter lines. 37 | for parameter in parameters 38 | typePadding = longestTypeLength - parameter.type.length 39 | variablePadding = longestNameLength - parameter.name.length 40 | 41 | type = parameter.type + ' '.repeat(typePadding) 42 | variable = parameter.name + ' '.repeat(variablePadding) 43 | 44 | lines.push("@param #{type} #{variable}#{descriptionPlaceholder}") 45 | 46 | if returnType? and returnType != 'void' 47 | if generateDescriptionPlaceholders or parameters.length > 0 48 | lines.push('') 49 | 50 | lines.push("@return #{returnType}") 51 | 52 | return @buildByLines(lines, tabText) 53 | 54 | ###* 55 | * @param {String|null} type 56 | * @param {boolean} generateDescriptionPlaceholders 57 | * @param {String} tabText 58 | * 59 | * @return {String} 60 | ### 61 | buildForProperty: (type, generateDescriptionPlaceholders = true, tabText = '') => 62 | lines = [] 63 | 64 | if generateDescriptionPlaceholders 65 | lines.push("[Short description of the property]") 66 | lines.push('') 67 | 68 | lines.push("@var #{type}") 69 | 70 | return @buildByLines(lines, tabText) 71 | 72 | ###* 73 | * @param {Array} lines 74 | * @param {String} tabText 75 | * 76 | * @return {String} 77 | ### 78 | buildByLines: (lines, tabText = '') => 79 | docs = @buildLine("/**", tabText) 80 | 81 | if lines.length == 0 82 | # Ensure we always have at least one line. 83 | lines.push('') 84 | 85 | for line in lines 86 | docs += @buildDocblockLine(line, tabText) 87 | 88 | docs += @buildLine(" */", tabText) 89 | 90 | return docs 91 | 92 | ###* 93 | * @param {String} content 94 | * @param {String} tabText 95 | * 96 | * @return {String} 97 | ### 98 | buildDocblockLine: (content, tabText = '') -> 99 | content = " * #{content}" 100 | 101 | return @buildLine(content.trimRight(), tabText) 102 | 103 | ###* 104 | * @param {String} content 105 | * @param {String} tabText 106 | * 107 | * @return {String} 108 | ### 109 | buildLine: (content, tabText = '') -> 110 | return "#{tabText}#{content}\n" 111 | -------------------------------------------------------------------------------- /lib/Utility/FunctionBuilder.coffee: -------------------------------------------------------------------------------- 1 | module.exports = 2 | 3 | class FunctionBuilder 4 | ###* 5 | * The access modifier (null if none). 6 | ### 7 | accessModifier: null 8 | 9 | ###* 10 | * Whether the method is static or not. 11 | ### 12 | isStatic: false 13 | 14 | ###* 15 | * Whether the method is abstract or not. 16 | ### 17 | isAbstract: null 18 | 19 | ###* 20 | * The name of the function. 21 | ### 22 | name: null 23 | 24 | ###* 25 | * The return type of the function. This could be set when generating PHP >= 7 methods. 26 | ### 27 | returnType: null 28 | 29 | ###* 30 | * The parameters of the function (a list of objects). 31 | ### 32 | parameters: null 33 | 34 | ###* 35 | * A list of statements to place in the body of the function. 36 | ### 37 | statements: null 38 | 39 | ###* 40 | * The tab text to insert on each line. 41 | ### 42 | tabText: '' 43 | 44 | ###* 45 | * The indentation level. 46 | ### 47 | indentationLevel: null 48 | 49 | ###* 50 | * The indentation level. 51 | * 52 | * @var {Number|null} 53 | ### 54 | maxLineLength: null 55 | 56 | ###* 57 | * Constructor. 58 | ### 59 | constructor: () -> 60 | @parameters = [] 61 | @statements = [] 62 | 63 | ###* 64 | * Makes the method public. 65 | * 66 | * @return {FunctionBuilder} 67 | ### 68 | makePublic: () -> 69 | @accessModifier = 'public' 70 | return this 71 | 72 | ###* 73 | * Makes the method private. 74 | * 75 | * @return {FunctionBuilder} 76 | ### 77 | makePrivate: () -> 78 | @accessModifier = 'private' 79 | return this 80 | 81 | ###* 82 | * Makes the method protected. 83 | * 84 | * @return {FunctionBuilder} 85 | ### 86 | makeProtected: () -> 87 | @accessModifier = 'protected' 88 | return this 89 | 90 | ###* 91 | * Makes the method global (i.e. no access modifier is added). 92 | * 93 | * @return {FunctionBuilder} 94 | ### 95 | makeGlobal: () -> 96 | @accessModifier = null 97 | return this 98 | 99 | ###* 100 | * Sets whether the method is static or not. 101 | * 102 | * @param {bool} isStatic 103 | * 104 | * @return {FunctionBuilder} 105 | ### 106 | setIsStatic: (@isStatic) -> 107 | return this 108 | 109 | ###* 110 | * Sets whether the method is abstract or not. 111 | * 112 | * @param {bool} isAbstract 113 | * 114 | * @return {FunctionBuilder} 115 | ### 116 | setIsAbstract: (@isAbstract) -> 117 | return this 118 | 119 | ###* 120 | * Sets the name of the function. 121 | * 122 | * @param {String} name 123 | * 124 | * @return {FunctionBuilder} 125 | ### 126 | setName: (@name) -> 127 | return this 128 | 129 | ###* 130 | * Sets the return type. 131 | * 132 | * @param {String|null} returnType 133 | * 134 | * @return {FunctionBuilder} 135 | ### 136 | setReturnType: (@returnType) -> 137 | return this 138 | 139 | ###* 140 | * Sets the parameters to add. 141 | * 142 | * @param {Array} parameters 143 | * 144 | * @return {FunctionBuilder} 145 | ### 146 | setParameters: (@parameters) -> 147 | return this 148 | 149 | ###* 150 | * Adds a parameter to the parameter list. 151 | * 152 | * @param {Object} parameter 153 | * 154 | * @return {FunctionBuilder} 155 | ### 156 | addParameter: (parameter) -> 157 | @parameters.push(parameter) 158 | return this 159 | 160 | ###* 161 | * Sets the statements to add. 162 | * 163 | * @param {Array} statements 164 | * 165 | * @return {FunctionBuilder} 166 | ### 167 | setStatements: (@statements) -> 168 | return this 169 | 170 | ###* 171 | * Adds a statement to the body of the function. 172 | * 173 | * @param {String} statement 174 | * 175 | * @return {FunctionBuilder} 176 | ### 177 | addStatement: (statement) -> 178 | @statements.push(statement) 179 | return this 180 | 181 | ###* 182 | * Sets the tab text to prepend to each line. 183 | * 184 | * @param {String} tabText 185 | * 186 | * @return {FunctionBuilder} 187 | ### 188 | setTabText: (@tabText) -> 189 | return this 190 | 191 | ###* 192 | * Sets the indentation level to use. The tab text is repeated this many times for each line. 193 | * 194 | * @param {Number} indentationLevel 195 | * 196 | * @return {FunctionBuilder} 197 | ### 198 | setIndentationLevel: (@indentationLevel) -> 199 | return this 200 | 201 | ###* 202 | * Sets the maximum length a single line may occupy. After this, text will wrap. 203 | * 204 | * This primarily influences parameter lists, which will automatically be split over multiple lines if the parameter 205 | * list would otherwise exceed the maximum length. 206 | * 207 | * @param {Number|null} maxLineLength The length or null to disable the maximum. 208 | * 209 | * @return {FunctionBuilder} 210 | ### 211 | setMaxLineLength: (@maxLineLength) -> 212 | return this 213 | 214 | ###* 215 | * Sets the parameters of the builder based on raw method data from the base service. 216 | * 217 | * @param {Object} data 218 | * 219 | * @return {FunctionBuilder} 220 | ### 221 | setFromRawMethodData: (data) -> 222 | if data.isPublic 223 | @makePublic() 224 | 225 | else if data.isProtected 226 | @makeProtected() 227 | 228 | else if data.isPrivate 229 | @makePrivate() 230 | 231 | else 232 | @makeGlobal() 233 | 234 | @setName(data.name) 235 | @setIsStatic(data.isStatic) 236 | @setIsAbstract(data.isAbstract) 237 | @setReturnType(data.returnTypeHint) 238 | 239 | parameters = [] 240 | 241 | for parameter in data.parameters 242 | parameters.push({ 243 | name : '$' + parameter.name 244 | typeHint : parameter.typeHint 245 | isVariadic : parameter.isVariadic 246 | isReference : parameter.isReference 247 | defaultValue : parameter.defaultValue 248 | }) 249 | 250 | @setParameters(parameters) 251 | 252 | return this 253 | 254 | ###* 255 | * Builds the method using the preconfigured settings. 256 | * 257 | * @return {String} 258 | ### 259 | build: () => 260 | output = '' 261 | 262 | signature = @buildSignature(false) 263 | 264 | if @maxLineLength? and signature.length > @maxLineLength 265 | output += @buildSignature(true) 266 | output += " {\n" 267 | 268 | else 269 | output += signature + "\n" 270 | output += @buildLine('{') 271 | 272 | for statement in @statements 273 | output += @tabText + @buildLine(statement) 274 | 275 | output += @buildLine('}') 276 | 277 | return output 278 | 279 | ###* 280 | * @param {Boolean} isMultiLine 281 | * 282 | * @return {String} 283 | ### 284 | buildSignature: (isMultiLine) -> 285 | signatureLine = '' 286 | 287 | if @isAbstract 288 | signatureLine += 'abstract ' 289 | 290 | if @accessModifier? 291 | signatureLine += "#{@accessModifier} " 292 | 293 | if @isStatic 294 | signatureLine += 'static ' 295 | 296 | signatureLine += "function #{@name}(" 297 | 298 | parameters = [] 299 | 300 | for parameter in @parameters 301 | parameterText = '' 302 | 303 | if parameter.typeHint? 304 | parameterText += "#{parameter.typeHint} " 305 | 306 | if parameter.isVariadic 307 | parameterText += '...' 308 | 309 | if parameter.isReference 310 | parameterText += '&' 311 | 312 | parameterText += "#{parameter.name}" 313 | 314 | if parameter.defaultValue? 315 | parameterText += " = #{parameter.defaultValue}" 316 | 317 | parameters.push(parameterText) 318 | 319 | if not isMultiLine 320 | signatureLine += parameters.join(', ') 321 | signatureLine += ')' 322 | 323 | signatureLine = @addTabText(signatureLine) 324 | 325 | else 326 | signatureLine = @buildLine(signatureLine) 327 | 328 | for i, parameter of parameters 329 | if i < (parameters.length - 1) 330 | parameter += ',' 331 | 332 | signatureLine += @buildLine(parameter, @indentationLevel + 1) 333 | 334 | signatureLine += @addTabText(')') 335 | 336 | if @returnType? 337 | signatureLine += ": #{@returnType}" 338 | 339 | return signatureLine 340 | 341 | ###* 342 | * @param {String} content 343 | * @param {Number|null} indentationLevel 344 | * 345 | * @return {String} 346 | ### 347 | buildLine: (content, indentationLevel = null) -> 348 | return @addTabText(content, indentationLevel) + "\n" 349 | 350 | ###* 351 | * @param {String} content 352 | * @param {Number|null} indentationLevel 353 | * 354 | * @return {String} 355 | ### 356 | addTabText: (content, indentationLevel = null) -> 357 | if not indentationLevel? 358 | indentationLevel = @indentationLevel 359 | 360 | tabText = @tabText.repeat(indentationLevel) 361 | 362 | return "#{tabText}#{content}" 363 | -------------------------------------------------------------------------------- /lib/Utility/MultiSelectionView.coffee: -------------------------------------------------------------------------------- 1 | {$, $$, SelectListView} = require 'atom-space-pen-views' 2 | 3 | module.exports = 4 | 5 | ##* 6 | # An extension on SelectListView from atom-space-pen-views that allows multiple selections. 7 | ## 8 | class MultiSelectionView extends SelectListView 9 | ###* 10 | * The callback to invoke when the user confirms his selections. 11 | ### 12 | onDidConfirm : null 13 | 14 | ###* 15 | * The callback to invoke when the user cancels the view. 16 | ### 17 | onDidCancel : null 18 | 19 | ###* 20 | * Metadata to pass to the callbacks. 21 | ### 22 | metadata : null 23 | 24 | ###* 25 | * The message to display when there are no results. 26 | ### 27 | emptyMessage : null 28 | 29 | ###* 30 | * Items that are currently selected. 31 | ### 32 | selectedItems : null 33 | 34 | ###* 35 | * Constructor. 36 | * 37 | * @param {Callback} onDidConfirm 38 | * @param {Callback} onDidCancel 39 | ### 40 | constructor: (@onDidConfirm, @onDidCancel = null) -> 41 | super() 42 | 43 | @selectedItems = [] 44 | 45 | ###* 46 | * @inheritdoc 47 | ### 48 | initialize: -> 49 | super() 50 | 51 | @addClass('php-integrator-refactoring-multi-selection-view') 52 | @list.addClass('mark-active') 53 | 54 | @panel ?= atom.workspace.addModalPanel(item: this, visible: false) 55 | 56 | @createWidgets() 57 | 58 | ###* 59 | * Destroys the view and cleans up. 60 | ### 61 | destroy: () -> 62 | @panel.destroy() 63 | @panel = null 64 | 65 | ###* 66 | * Creates additional for the view. 67 | ### 68 | createWidgets: () -> 69 | cancelButtonText = @getCancelButtonText() 70 | confirmButtonText = @getConfirmButtonText() 71 | 72 | buttonBar = $$ -> 73 | @div class: 'button-bar', => 74 | @button class: 'btn btn-error inline-block-tight pull-left icon icon-circle-slash button--cancel', cancelButtonText 75 | @button class: 'btn btn-success inline-block-tight pull-right icon icon-gear button--confirm', confirmButtonText 76 | @div class: 'clear-float' 77 | 78 | buttonBar.appendTo(this) 79 | 80 | @on 'click', 'button', (event) => 81 | @confirmedByButton() if $(event.target).hasClass('button--confirm') 82 | @cancel() if $(event.target).hasClass('button--cancel') 83 | 84 | @on 'keydown', (event) => 85 | # Shift + Return 86 | if event.keyCode == 13 and event.shiftKey == true 87 | @confirmedByButton() 88 | 89 | # Ensure that button clicks are actually handled. 90 | @on 'mousedown', ({target}) => 91 | return false if $(target).hasClass('btn') 92 | 93 | ###* 94 | * @inheritdoc 95 | ### 96 | viewForItem: (item) -> 97 | classes = ['list-item'] 98 | 99 | if item.className 100 | classes.push(item.className) 101 | 102 | if item.isSelected 103 | classes.push('active') 104 | 105 | className = classes.join(' ') 106 | displayText = item.name 107 | 108 | return """ 109 |
  • #{displayText}
  • 110 | """ 111 | 112 | ###* 113 | * @inheritdoc 114 | ### 115 | getFilterKey: () -> 116 | return 'name' 117 | 118 | ###* 119 | * Retrieves the text to display on the cancel button. 120 | * 121 | * @return {string} 122 | ### 123 | getCancelButtonText: () -> 124 | return 'Cancel' 125 | 126 | ###* 127 | * Retrieves the text to display on the confirmation button. 128 | * 129 | * @return {string} 130 | ### 131 | getConfirmButtonText: () -> 132 | return 'Generate' 133 | 134 | ###* 135 | * Retrieves the message that is displayed when there are no results. 136 | * 137 | * @return {string} 138 | ### 139 | getEmptyMessage: () -> 140 | if @emptyMessage? 141 | return @emptyMessage 142 | 143 | return super() 144 | 145 | ###* 146 | * Sets the message that is displayed when there are no results. 147 | * 148 | * @param {string} emptyMessage 149 | ### 150 | setEmptyMessage: (emptyMessage) -> 151 | @emptyMessage = emptyMessage 152 | 153 | ###* 154 | * Retrieves the metadata to pass to the callbacks. 155 | * 156 | * @return {Object|null} 157 | ### 158 | getMetadata: () -> 159 | return @metadata 160 | 161 | ###* 162 | * Sets the metadata to pass to the callbacks. 163 | * 164 | * @param {Object|null} metadata 165 | ### 166 | setMetadata: (metadata) -> 167 | @metadata = metadata 168 | 169 | ###* 170 | * @inheritdoc 171 | ### 172 | setItems: (items) -> 173 | i = 0 174 | 175 | for item in items 176 | item.index = i++ 177 | 178 | super(items) 179 | 180 | @selectedItems = [] 181 | 182 | ###* 183 | * @inheritdoc 184 | ### 185 | confirmed: (item) -> 186 | item.isSelected = not item.isSelected 187 | 188 | if item.isSelected 189 | @selectedItems.push(item) 190 | 191 | else 192 | index = @selectedItems.indexOf(item) 193 | 194 | if index >= 0 195 | @selectedItems.splice(index, 1) 196 | 197 | selectedItem = @getSelectedItem() 198 | index = if selectedItem then selectedItem.index else 0 199 | 200 | @populateList() 201 | 202 | @selectItemView(@list.find("li:nth(#{index})")) 203 | 204 | ###* 205 | * Invoked when the user confirms his selections by pressing the confirmation button. 206 | ### 207 | confirmedByButton: () -> 208 | @invokeOnDidConfirm() 209 | @restoreFocus() 210 | @panel.hide() 211 | 212 | ###* 213 | * Invokes the on did confirm handler with the correct arguments (if it is set). 214 | ### 215 | invokeOnDidConfirm: () -> 216 | if @onDidConfirm 217 | @onDidConfirm(@selectedItems, @getMetadata()) 218 | 219 | ###* 220 | * @inheritdoc 221 | ### 222 | cancelled: () -> 223 | if @onDidCancel 224 | @onDidCancel(@getMetadata()) 225 | 226 | @restoreFocus() 227 | @panel.hide() 228 | 229 | ###* 230 | * Presents the view to the user. 231 | ### 232 | present: () -> 233 | @panel.show() 234 | @focusFilterEditor() 235 | -------------------------------------------------------------------------------- /lib/Utility/TypeHelper.coffee: -------------------------------------------------------------------------------- 1 | module.exports = 2 | 3 | class TypeHelper 4 | ###* 5 | * @var {Object|null} service 6 | ### 7 | service: null 8 | 9 | ###* 10 | * @param {Object} service 11 | ### 12 | setService: (@service) -> 13 | 14 | ###* 15 | * @return {Number} 16 | ### 17 | getCurrentProjectPhpVersion: () -> 18 | projectSettings = @service.getCurrentProjectSettings() 19 | 20 | if projectSettings? 21 | return projectSettings.phpVersion 22 | 23 | return 5.2 # Assume lowest supported version 24 | 25 | ###* 26 | * @param {String|null} typeSpecification 27 | * 28 | * @return {Object|null} 29 | ### 30 | getReturnTypeHintForTypeSpecification: (typeSpecification) -> 31 | return null if @getCurrentProjectPhpVersion() < 7.0 32 | 33 | returnTypeHint = @getTypeHintForTypeSpecification(typeSpecification) 34 | 35 | if not returnTypeHint? or returnTypeHint.shouldSetDefaultValueToNull 36 | return null 37 | 38 | return returnTypeHint.typeHint 39 | 40 | ###* 41 | * @param {String|null} typeSpecification 42 | * 43 | * @return {Object|null} 44 | ### 45 | getTypeHintForTypeSpecification: (typeSpecification) -> 46 | types = @getDocblockTypesFromDocblockTypeSpecification(typeSpecification) 47 | 48 | return @getTypeHintForDocblockTypes(types) 49 | 50 | ###* 51 | * @param {String|null} typeSpecification 52 | * 53 | * @return {Array} 54 | ### 55 | getDocblockTypesFromDocblockTypeSpecification: (typeSpecification) -> 56 | return [] if not typeSpecification? 57 | return typeSpecification.split('|') 58 | 59 | ###* 60 | * @param {Array} types 61 | * @param {boolean} allowPhp7 62 | * 63 | * @return {Object|null} 64 | ### 65 | getTypeHintForDocblockTypes: (types) -> 66 | isNullable = false 67 | 68 | types = types.filter (type) => 69 | if type == 'null' 70 | isNullable = true 71 | 72 | return type != 'null' 73 | 74 | typeHint = null 75 | previousTypeHint = null 76 | 77 | for type in types 78 | typeHint = @getTypeHintForDocblockType(type) 79 | 80 | if previousTypeHint? and typeHint != previousTypeHint 81 | # Several different type hints are necessary, we can't provide a common denominator. 82 | return null 83 | 84 | previousTypeHint = typeHint 85 | 86 | data = { 87 | typeHint : typeHint 88 | shouldSetDefaultValueToNull : false 89 | } 90 | 91 | return data if not typeHint? 92 | return data if not isNullable 93 | 94 | currentPhpVersion = @getCurrentProjectPhpVersion() 95 | 96 | if currentPhpVersion >= 7.1 97 | data.typeHint = '?' + typeHint 98 | data.shouldSetDefaultValueToNull = false 99 | 100 | else 101 | data.shouldSetDefaultValueToNull = true 102 | 103 | return data 104 | 105 | ###* 106 | * @param {String|null} type 107 | * 108 | * @return {String|null} 109 | ### 110 | getTypeHintForDocblockType: (type) -> 111 | return null if not type? 112 | return type if @isClassType(type) 113 | return @getScalarTypeHintForDocblockType(type) 114 | 115 | ###* 116 | * @param {String|null} type 117 | * 118 | * @return {boolean} 119 | ### 120 | isClassType: (type) -> 121 | return if (@getScalarTypeHintForDocblockType(type) == false) then true else false 122 | 123 | ###* 124 | * @param {String|null} type 125 | * 126 | * @return {String|null|false} Null if the type is recognized, but there is no type hint available, false of the 127 | * type is not recognized at all, and the type hint itself if it is recognized and there 128 | * is a type hint. 129 | ### 130 | getScalarTypeHintForDocblockType: (type) -> 131 | return null if not type? 132 | 133 | phpVersion = @getCurrentProjectPhpVersion() 134 | 135 | if phpVersion >= 7.1 136 | return 'iterable' if type == 'iterable' 137 | return 'void' if type == 'void' 138 | 139 | else if phpVersion >= 7.0 140 | return 'string' if type == 'string' 141 | return 'int' if type == 'int' 142 | return 'bool' if type == 'bool' 143 | return 'float' if type == 'float' 144 | return 'resource' if type == 'resource' 145 | return 'bool' if type == 'false' 146 | return 'bool' if type == 'true' 147 | 148 | else 149 | return null if type == 'string' 150 | return null if type == 'int' 151 | return null if type == 'bool' 152 | return null if type == 'float' 153 | return null if type == 'resource' 154 | return null if type == 'false' 155 | return null if type == 'true' 156 | 157 | return 'array' if type == 'array' 158 | return 'callable' if type == 'callable' 159 | return 'self' if type == 'self' 160 | return 'self' if type == 'static' 161 | return 'array' if /^.+\[\]$/.test(type) 162 | 163 | return null if type == 'object' 164 | return null if type == 'mixed' 165 | return null if type == 'void' 166 | return null if type == 'null' 167 | return null if type == 'parent' 168 | return null if type == '$this' 169 | 170 | return false 171 | 172 | ###* 173 | * Takes a type list (list of type objects) and turns them into a single docblock type specification. 174 | * 175 | * @param {Array} typeList 176 | * 177 | * @return {String} 178 | ### 179 | buildTypeSpecificationFromTypeArray: (typeList) -> 180 | typeNames = typeList.map (type) -> 181 | return type.type 182 | 183 | return @buildTypeSpecificationFromTypes(typeNames) 184 | 185 | ###* 186 | * Takes a list of type names and turns them into a single docblock type specification. 187 | * 188 | * @param {Array} typeNames 189 | * 190 | * @return {String} 191 | ### 192 | buildTypeSpecificationFromTypes: (typeNames) -> 193 | return 'mixed' if typeNames.length == 0 194 | 195 | return typeNames.join('|') 196 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "php-integrator-refactoring", 3 | "main": "./lib/Main", 4 | "version": "1.4.1", 5 | "description": "Provides refactoring capabilities for your PHP source code.", 6 | "repository": "php-integrator/atom-refactoring", 7 | "license": "GPL-3.0", 8 | "engines": { 9 | "atom": ">=1.13.0 <2.0.0" 10 | }, 11 | "consumedServices": { 12 | "php-integrator.service": { 13 | "versions": { 14 | "^3.0": "setService" 15 | } 16 | }, 17 | "snippets": { 18 | "versions": { 19 | "0.1.0": "setSnippetManager" 20 | } 21 | } 22 | }, 23 | "providedServices": { 24 | "intentions:list": { 25 | "versions": { 26 | "1.0.0": "provideIntentions" 27 | } 28 | } 29 | }, 30 | "dependencies": { 31 | "atom-package-deps": "^4.3.1", 32 | "atom-space-pen-views": "~2.2" 33 | }, 34 | "package-deps": [ 35 | "intentions" 36 | ], 37 | "keywords": [ 38 | "php", 39 | "refactoring", 40 | "integrator", 41 | "integration", 42 | "php-integrator" 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /styles/main.less: -------------------------------------------------------------------------------- 1 | // The ui-variables file is provided by base themes provided by Atom. 2 | // 3 | // See https://github.com/atom/atom-dark-ui/blob/master/stylesheets/ui-variables.less 4 | // for a full listing of what's available. 5 | @import "ui-variables"; 6 | @import "octicon-utf-codes"; 7 | 8 | .php-integrator-refactoring-strikethrough { 9 | text-decoration: line-through; 10 | } 11 | 12 | .php-integrator-refactoring-multi-selection-view { 13 | .list-item { 14 | 15 | } 16 | 17 | .checkbox { 18 | font-size: x-small; 19 | } 20 | 21 | .text-line { 22 | // margin-top: 0.5em; 23 | } 24 | 25 | .button-bar { 26 | // margin-top: 0.5em; 27 | 28 | .clear-float { 29 | clear: both; 30 | } 31 | } 32 | } 33 | 34 | .php-integrator-refactoring-extract-method { 35 | .section-body, .form-control, .control-label, .control-group, .controls { 36 | width: 100%; 37 | } 38 | .preview-area { 39 | atom-text-editor .editor-contents--private { 40 | max-height: 400px !important; 41 | } 42 | } 43 | // Should change to reflect the padding of the theme instead of hardcoded. 44 | .block { 45 | margin-top: 4px; 46 | } 47 | .pull-right { 48 | .inline-block { 49 | margin-left: 9px; 50 | } 51 | } 52 | 53 | .checkbox { 54 | // Removing any extra margining to the checkboxes (e.g. Atom Material) 55 | margin-top: 5px; 56 | margin-bottom: 5px; 57 | } 58 | 59 | .settings-view .section-body { 60 | margin-top: 0px; 61 | } 62 | 63 | .button-bar { 64 | .clear-float { 65 | clear: both; 66 | } 67 | } 68 | } 69 | --------------------------------------------------------------------------------