├── .gitignore ├── LICENSE.txt ├── README.md ├── composer.json └── src ├── Drupal └── Core │ ├── Template │ ├── Attribute.php │ ├── AttributeArray.php │ ├── AttributeBoolean.php │ ├── AttributeString.php │ └── AttributeValueBase.php │ └── Url.php └── aleksip └── DataTransformPlugin ├── DataTransformPlugin.php ├── DataTransformer.php ├── ErrorHandlerTrait.php ├── PatternLabListener.php ├── Renderer.php └── Twig ├── PatternDataEmbedNode.php ├── PatternDataIncludeNode.php ├── PatternDataNodeTrait.php ├── PatternDataNodeVisitor.php └── TwigEnvironmentDecorator.php /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | vendor 3 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Transform Plugin for Pattern Lab 2 | 3 | ## Installation 4 | 5 | To install and use the plugin run the following command in the Pattern Lab root directory: 6 | 7 | ```sh 8 | composer require aleksip/plugin-data-transform 9 | ``` 10 | 11 | 12 | ## Configuration options 13 | 14 | For `Attribute` object support to work properly, your Pattern Lab `config.yml` file needs to have the following setting: 15 | 16 | ```yaml 17 | twigAutoescape: false 18 | ``` 19 | 20 | The default values for Data Transform Plugin specific options in `config.yml` are: 21 | 22 | ```yaml 23 | plugins: 24 | dataTransform: 25 | enabled: true 26 | verbose: false 27 | ``` 28 | 29 | 30 | ### Enabling and disabling the plugin 31 | 32 | Once installed, it is possible to enable and disable Data Transform Plugin using the `enabled` setting. 33 | 34 | 35 | ### Verbose mode 36 | 37 | Occasionally it might happen that there is a problem with a data file, and PHP notices and/or warnings with long stack traces are displayed when Pattern Lab is generated. In a large project it can be difficult to find the problematic data file, but turning on Data Transform Plugin's verbose mode using the `verbose` setting can help. 38 | 39 | In verbose mode Data Transform plugin reports each pattern it processes and all data transform functions performed. It also suppresses regular PHP error messages and reports about errors in an easier to read way. 40 | 41 | Important note: due to the way verbose mode is implemented, it might not work if other plugins that interact with the Twig `Environment` object are used. 42 | 43 | 44 | ## Features 45 | 46 | ### Pattern-specific data file support for included patterns 47 | 48 | Pattern Lab core only supports global data files and a pattern-specific data file for the main pattern. This plugin adds pattern-specific data file support for included patterns. This feature works with the include function provided by this plugin with all PatternEngines and also with regular includes in template files with Twig PatternEngine. 49 | 50 | Please note that global data from the `_data` directory is considered to be pattern-specific data and will overwrite data inherited from a parent pattern. If you want to override data of an included pattern you can use the `with` keyword. 51 | 52 | 53 | ### Data transform functions 54 | 55 | Currently the plugin provides four transform functions for the data read by Pattern Lab. The examples provided are in JSON but Pattern Lab supports YAML too. 56 | 57 | 58 | #### Include pattern files 59 | 60 | If a value contains the name of a pattern in shorthand partials syntax, the plugin will replace the value with the rendered pattern: 61 | 62 | ```json 63 | { 64 | "key": "atoms-form-element-label-html" 65 | } 66 | ``` 67 | 68 | Advanced syntax with support for passing variables (`with`) and disabling access to the default data (`only`): 69 | 70 | ```json 71 | { 72 | "key": { 73 | "include()": { 74 | "pattern": "atoms-form-element-label-html", 75 | "with": { 76 | "title": "Textfield label" 77 | }, 78 | "only": true 79 | } 80 | } 81 | } 82 | ``` 83 | 84 | In both examples the value of `key` will replaced with the rendered pattern. 85 | 86 | For more information about `with` and `only` please refer to the [Twig `include` documentation](https://twig.symfony.com/doc/2.x/tags/include.html). 87 | 88 | 89 | #### Include pseudo-pattern files 90 | 91 | It is also possible to include [pseudo-patterns](http://patternlab.io/docs/pattern-pseudo-patterns.html) using the shorthand partials syntax, by replacing the tilde (~) with a dash (-). So for example the pseudo-pattern `shila-card.html~variant.json` can be included like so: 92 | 93 | ```json 94 | { 95 | "key": "molecules-shila-card-html-variant" 96 | } 97 | ``` 98 | 99 | 100 | #### Join text values 101 | 102 | ```json 103 | { 104 | "key": { 105 | "join()": [ 106 | "molecules-comment-html", 107 | "
", 108 | "molecules-comment-html", 109 | "
", 110 | "molecules-comment-html" 111 | ] 112 | } 113 | } 114 | ``` 115 | 116 | The value of `key` will be replaced with the joined strings. Note that in the example `molecules-comment-html` is the name of a pattern in shorthand partials syntax. These will be replaced with the rendered pattern before the join. 117 | 118 | 119 | #### Create Drupal `Attribute` objects 120 | 121 | ```json 122 | { 123 | "key": { 124 | "Attribute()": { 125 | "id": ["edit-submit"], 126 | "type": ["submit"], 127 | "value": ["Submit"], 128 | "class": ["button", "button-primary"] 129 | } 130 | } 131 | } 132 | ``` 133 | 134 | The value of `key` will be replaced with an [`Attribute` object](https://www.drupal.org/node/2513632). 135 | 136 | 137 | #### Create Drupal `Url` objects 138 | 139 | ```json 140 | { 141 | "key": { 142 | "Url()": { 143 | "url": "http://example.com", 144 | "options": { 145 | "attributes": { 146 | "Attribute()": { 147 | "class": ["link"] 148 | } 149 | } 150 | } 151 | } 152 | } 153 | } 154 | ``` 155 | 156 | The value of `key` will be replaced with an `Url` object. Note that in the example the value of `attributes` will be replaced with an `Attribute` object before the `Url` object is created. 157 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "aleksip/plugin-data-transform", 3 | "description": "Data Transform Plugin for Pattern Lab PHP", 4 | "keywords": ["pattern lab", "plugin", "drupal"], 5 | "homepage": "https://github.com/aleksip/plugin-data-transform", 6 | "license": "GPL-2.0-or-later", 7 | "type": "patternlab-plugin", 8 | "authors": [ 9 | { 10 | "name": "Aleksi Peebles" 11 | } 12 | ], 13 | "support": { 14 | "issues": "https://github.com/aleksip/plugin-data-transform/issues", 15 | "source": "https://github.com/aleksip/plugin-data-transform/releases" 16 | }, 17 | "autoload": { 18 | "psr-0": { 19 | "aleksip\\DataTransformPlugin\\": "src/", 20 | "Drupal\\Component\\Render\\": "src/", 21 | "Drupal\\Component\\Utility\\": "src/", 22 | "Drupal\\Core\\": "src/", 23 | "Drupal\\Core\\Template\\": "src/" 24 | } 25 | }, 26 | "require": { 27 | "php": ">=5.5.9", 28 | "pattern-lab/core": "^2.6.3", 29 | "drupal/core-render": "^8.7", 30 | "drupal/core-utility": "^8.7" 31 | }, 32 | "extra": { 33 | "patternlab": { 34 | "config": { 35 | "plugins": { 36 | "dataTransform": { 37 | "enabled": true, 38 | "verbose": false 39 | } 40 | } 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Drupal/Core/Template/Attribute.php: -------------------------------------------------------------------------------- 1 | 'socks')); 15 | * $attributes['class'] = array('black-cat', 'white-cat'); 16 | * $attributes['class'][] = 'black-white-cat'; 17 | * echo ''; 18 | * // Produces 19 | * @endcode 20 | * 21 | * $attributes always prints out all the attributes. For example: 22 | * @code 23 | * $attributes = new Attribute(array('id' => 'socks')); 24 | * $attributes['class'] = array('black-cat', 'white-cat'); 25 | * $attributes['class'][] = 'black-white-cat'; 26 | * echo ''; 27 | * // Produces 28 | * @endcode 29 | * 30 | * When printing out individual attributes to customize them within a Twig 31 | * template, use the "without" filter to prevent attributes that have already 32 | * been printed from being printed again. For example: 33 | * @code 34 | * 35 | * {# Produces #} 36 | * @endcode 37 | * 38 | * The attribute keys and values are automatically escaped for output with 39 | * Html::escape(). No protocol filtering is applied, so when using user-entered 40 | * input as a value for an attribute that expects an URI (href, src, ...), 41 | * UrlHelper::stripDangerousProtocols() should be used to ensure dangerous 42 | * protocols (such as 'javascript:') are removed. For example: 43 | * @code 44 | * $path = 'javascript:alert("xss");'; 45 | * $path = UrlHelper::stripDangerousProtocols($path); 46 | * $attributes = new Attribute(array('href' => $path)); 47 | * echo ''; 48 | * // Produces 49 | * @endcode 50 | * 51 | * The attribute values are considered plain text and are treated as such. If a 52 | * safe HTML string is detected, it is converted to plain text with 53 | * PlainTextOutput::renderFromHtml() before being escaped. For example: 54 | * @code 55 | * $value = t('Highlight the @tag tag', ['@tag' => '']); 56 | * $attributes = new Attribute(['value' => $value]); 57 | * echo ''; 58 | * // Produces 59 | * @endcode 60 | * 61 | * @see \Drupal\Component\Utility\Html::escape() 62 | * @see \Drupal\Component\Render\PlainTextOutput::renderFromHtml() 63 | * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() 64 | */ 65 | class Attribute implements \ArrayAccess, \IteratorAggregate, MarkupInterface { 66 | 67 | /** 68 | * Stores the attribute data. 69 | * 70 | * @var \Drupal\Core\Template\AttributeValueBase[] 71 | */ 72 | protected $storage = []; 73 | 74 | /** 75 | * Constructs a \Drupal\Core\Template\Attribute object. 76 | * 77 | * @param array $attributes 78 | * An associative array of key-value pairs to be converted to attributes. 79 | */ 80 | public function __construct($attributes = []) { 81 | foreach ($attributes as $name => $value) { 82 | $this->offsetSet($name, $value); 83 | } 84 | } 85 | 86 | /** 87 | * {@inheritdoc} 88 | */ 89 | public function offsetGet($name) { 90 | if (isset($this->storage[$name])) { 91 | return $this->storage[$name]; 92 | } 93 | } 94 | 95 | /** 96 | * {@inheritdoc} 97 | */ 98 | public function offsetSet($name, $value) { 99 | $this->storage[$name] = $this->createAttributeValue($name, $value); 100 | } 101 | 102 | /** 103 | * Creates the different types of attribute values. 104 | * 105 | * @param string $name 106 | * The attribute name. 107 | * @param mixed $value 108 | * The attribute value. 109 | * 110 | * @return \Drupal\Core\Template\AttributeValueBase 111 | * An AttributeValueBase representation of the attribute's value. 112 | */ 113 | protected function createAttributeValue($name, $value) { 114 | // If the value is already an AttributeValueBase object, 115 | // return a new instance of the same class, but with the new name. 116 | if ($value instanceof AttributeValueBase) { 117 | $class = get_class($value); 118 | return new $class($name, $value->value()); 119 | } 120 | // An array value or 'class' attribute name are forced to always be an 121 | // AttributeArray value for consistency. 122 | if ($name == 'class' && !is_array($value)) { 123 | // Cast the value to string in case it implements MarkupInterface. 124 | $value = [(string) $value]; 125 | } 126 | if (is_array($value)) { 127 | // Cast the value to an array if the value was passed in as a string. 128 | // @todo Decide to fix all the broken instances of class as a string 129 | // in core or cast them. 130 | $value = new AttributeArray($name, $value); 131 | } 132 | elseif (is_bool($value)) { 133 | $value = new AttributeBoolean($name, $value); 134 | } 135 | // As a development aid, we allow the value to be a safe string object. 136 | elseif ($value instanceof MarkupInterface) { 137 | // Attributes are not supposed to display HTML markup, so we just convert 138 | // the value to plain text. 139 | $value = PlainTextOutput::renderFromHtml($value); 140 | $value = new AttributeString($name, $value); 141 | } 142 | elseif (!is_object($value)) { 143 | $value = new AttributeString($name, $value); 144 | } 145 | return $value; 146 | } 147 | 148 | /** 149 | * {@inheritdoc} 150 | */ 151 | public function offsetUnset($name) { 152 | unset($this->storage[$name]); 153 | } 154 | 155 | /** 156 | * {@inheritdoc} 157 | */ 158 | public function offsetExists($name) { 159 | return isset($this->storage[$name]); 160 | } 161 | 162 | /** 163 | * Adds classes or merges them on to array of existing CSS classes. 164 | * 165 | * @param string|array ... 166 | * CSS classes to add to the class attribute array. 167 | * 168 | * @return $this 169 | */ 170 | public function addClass() { 171 | $args = func_get_args(); 172 | if ($args) { 173 | $classes = []; 174 | foreach ($args as $arg) { 175 | // Merge the values passed in from the classes array. 176 | // The argument is cast to an array to support comma separated single 177 | // values or one or more array arguments. 178 | $classes = array_merge($classes, (array) $arg); 179 | } 180 | 181 | // Merge if there are values, just add them otherwise. 182 | if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { 183 | // Merge the values passed in from the class value array. 184 | $classes = array_merge($this->storage['class']->value(), $classes); 185 | $this->storage['class']->exchangeArray($classes); 186 | } 187 | else { 188 | $this->offsetSet('class', $classes); 189 | } 190 | } 191 | 192 | return $this; 193 | } 194 | 195 | /** 196 | * Sets values for an attribute key. 197 | * 198 | * @param string $attribute 199 | * Name of the attribute. 200 | * @param string|array $value 201 | * Value(s) to set for the given attribute key. 202 | * 203 | * @return $this 204 | */ 205 | public function setAttribute($attribute, $value) { 206 | $this->offsetSet($attribute, $value); 207 | 208 | return $this; 209 | } 210 | 211 | /** 212 | * Removes an attribute from an Attribute object. 213 | * 214 | * @param string|array ... 215 | * Attributes to remove from the attribute array. 216 | * 217 | * @return $this 218 | */ 219 | public function removeAttribute() { 220 | $args = func_get_args(); 221 | foreach ($args as $arg) { 222 | // Support arrays or multiple arguments. 223 | if (is_array($arg)) { 224 | foreach ($arg as $value) { 225 | unset($this->storage[$value]); 226 | } 227 | } 228 | else { 229 | unset($this->storage[$arg]); 230 | } 231 | } 232 | 233 | return $this; 234 | } 235 | 236 | /** 237 | * Removes argument values from array of existing CSS classes. 238 | * 239 | * @param string|array ... 240 | * CSS classes to remove from the class attribute array. 241 | * 242 | * @return $this 243 | */ 244 | public function removeClass() { 245 | // With no class attribute, there is no need to remove. 246 | if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { 247 | $args = func_get_args(); 248 | $classes = []; 249 | foreach ($args as $arg) { 250 | // Merge the values passed in from the classes array. 251 | // The argument is cast to an array to support comma separated single 252 | // values or one or more array arguments. 253 | $classes = array_merge($classes, (array) $arg); 254 | } 255 | 256 | // Remove the values passed in from the value array. Use array_values() to 257 | // ensure that the array index remains sequential. 258 | $classes = array_values(array_diff($this->storage['class']->value(), $classes)); 259 | $this->storage['class']->exchangeArray($classes); 260 | } 261 | return $this; 262 | } 263 | 264 | /** 265 | * Gets the class attribute value if set. 266 | * 267 | * This method is implemented to take precedence over hasClass() for Twig 2.0. 268 | * 269 | * @return \Drupal\Core\Template\AttributeValueBase 270 | * The class attribute value if set. 271 | * 272 | * @see twig_get_attribute() 273 | */ 274 | public function getClass() { 275 | return $this->offsetGet('class'); 276 | } 277 | 278 | /** 279 | * Checks if the class array has the given CSS class. 280 | * 281 | * @param string $class 282 | * The CSS class to check for. 283 | * 284 | * @return bool 285 | * Returns TRUE if the class exists, or FALSE otherwise. 286 | */ 287 | public function hasClass($class) { 288 | if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { 289 | return in_array($class, $this->storage['class']->value()); 290 | } 291 | else { 292 | return FALSE; 293 | } 294 | } 295 | 296 | /** 297 | * Implements the magic __toString() method. 298 | */ 299 | public function __toString() { 300 | $return = ''; 301 | /** @var \Drupal\Core\Template\AttributeValueBase $value */ 302 | foreach ($this->storage as $name => $value) { 303 | $rendered = $value->render(); 304 | if ($rendered) { 305 | $return .= ' ' . $rendered; 306 | } 307 | } 308 | return $return; 309 | } 310 | 311 | /** 312 | * Returns all storage elements as an array. 313 | * 314 | * @return array 315 | * An associative array of attributes. 316 | */ 317 | public function toArray() { 318 | $return = []; 319 | foreach ($this->storage as $name => $value) { 320 | $return[$name] = $value->value(); 321 | } 322 | 323 | return $return; 324 | } 325 | 326 | /** 327 | * Implements the magic __clone() method. 328 | */ 329 | public function __clone() { 330 | foreach ($this->storage as $name => $value) { 331 | $this->storage[$name] = clone $value; 332 | } 333 | } 334 | 335 | /** 336 | * {@inheritdoc} 337 | */ 338 | public function getIterator() { 339 | return new \ArrayIterator($this->storage); 340 | } 341 | 342 | /** 343 | * Returns the whole array. 344 | */ 345 | public function storage() { 346 | return $this->storage; 347 | } 348 | 349 | /** 350 | * Returns a representation of the object for use in JSON serialization. 351 | * 352 | * @return string 353 | * The safe string content. 354 | */ 355 | public function jsonSerialize() { 356 | return (string) $this; 357 | } 358 | 359 | } 360 | -------------------------------------------------------------------------------- /src/Drupal/Core/Template/AttributeArray.php: -------------------------------------------------------------------------------- 1 | value[$offset]; 40 | } 41 | 42 | /** 43 | * {@inheritdoc} 44 | */ 45 | public function offsetSet($offset, $value) { 46 | if (isset($offset)) { 47 | $this->value[$offset] = $value; 48 | } 49 | else { 50 | $this->value[] = $value; 51 | } 52 | } 53 | 54 | /** 55 | * {@inheritdoc} 56 | */ 57 | public function offsetUnset($offset) { 58 | unset($this->value[$offset]); 59 | } 60 | 61 | /** 62 | * {@inheritdoc} 63 | */ 64 | public function offsetExists($offset) { 65 | return isset($this->value[$offset]); 66 | } 67 | 68 | /** 69 | * Implements the magic __toString() method. 70 | */ 71 | public function __toString() { 72 | // Filter out any empty values before printing. 73 | $this->value = array_unique(array_filter($this->value)); 74 | return Html::escape(implode(' ', $this->value)); 75 | } 76 | 77 | /** 78 | * {@inheritdoc} 79 | */ 80 | public function getIterator() { 81 | return new \ArrayIterator($this->value); 82 | } 83 | 84 | /** 85 | * Exchange the array for another one. 86 | * 87 | * @see ArrayObject::exchangeArray 88 | * 89 | * @param array $input 90 | * The array input to replace the internal value. 91 | * 92 | * @return array 93 | * The old array value. 94 | */ 95 | public function exchangeArray($input) { 96 | $old = $this->value; 97 | $this->value = $input; 98 | return $old; 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/Drupal/Core/Template/AttributeBoolean.php: -------------------------------------------------------------------------------- 1 | '; 19 | * // produces ; 23 | * @endcode 24 | * 25 | * @see \Drupal\Core\Template\Attribute 26 | */ 27 | class AttributeBoolean extends AttributeValueBase { 28 | 29 | /** 30 | * {@inheritdoc} 31 | */ 32 | public function render() { 33 | return $this->__toString(); 34 | } 35 | 36 | /** 37 | * Implements the magic __toString() method. 38 | */ 39 | public function __toString() { 40 | return $this->value === FALSE ? '' : Html::escape($this->name); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/Drupal/Core/Template/AttributeString.php: -------------------------------------------------------------------------------- 1 | '; 17 | * // Produces: . 18 | * @endcode 19 | * 20 | * @see \Drupal\Core\Template\Attribute 21 | */ 22 | class AttributeString extends AttributeValueBase { 23 | 24 | /** 25 | * Implements the magic __toString() method. 26 | */ 27 | public function __toString() { 28 | return Html::escape($this->value); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/Drupal/Core/Template/AttributeValueBase.php: -------------------------------------------------------------------------------- 1 | name = $name; 40 | $this->value = $value; 41 | } 42 | 43 | /** 44 | * Returns a string representation of the attribute. 45 | * 46 | * While __toString only returns the value in a string form, render() 47 | * contains the name of the attribute as well. 48 | * 49 | * @return string 50 | * The string representation of the attribute. 51 | */ 52 | public function render() { 53 | $value = (string) $this; 54 | if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) { 55 | return Html::escape($this->name) . '="' . $value . '"'; 56 | } 57 | } 58 | 59 | /** 60 | * Returns the raw value. 61 | */ 62 | public function value() { 63 | return $this->value; 64 | } 65 | 66 | /** 67 | * Implements the magic __toString() method. 68 | */ 69 | abstract public function __toString(); 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/Drupal/Core/Url.php: -------------------------------------------------------------------------------- 1 | uri = $uri; 46 | $this->options = $options; 47 | } 48 | 49 | /** 50 | * Creates a new Url object from a URI. 51 | * 52 | * @param string $uri 53 | * The URI of the resource including the scheme. 54 | * @param array $options 55 | * (optional) An associative array of additional URL options, with the 56 | * following elements: 57 | * - 'attributes': An associative array of HTML attributes that will be 58 | * added to the anchor tag if you use the \Drupal\Core\Link class to make 59 | * the link. 60 | * 61 | * @return \Drupal\Core\Url 62 | * A new Url object. 63 | */ 64 | public static function fromUri($uri, $options = []) { 65 | $url = new static($uri, $options); 66 | 67 | return $url; 68 | } 69 | 70 | /** 71 | * Returns the URL options. 72 | * 73 | * @return array 74 | * The array of options. See \Drupal\Core\Url::fromUri() for details on what 75 | * it contains. 76 | */ 77 | public function getOptions() { 78 | return $this->options; 79 | } 80 | 81 | /** 82 | * Gets a specific option. 83 | * 84 | * See \Drupal\Core\Url::fromUri() for details on the options. 85 | * 86 | * @param string $name 87 | * The name of the option. 88 | * 89 | * @return mixed 90 | * The value for a specific option, or NULL if it does not exist. 91 | */ 92 | public function getOption($name) { 93 | if (!isset($this->options[$name])) { 94 | return NULL; 95 | } 96 | 97 | return $this->options[$name]; 98 | } 99 | 100 | /** 101 | * Sets the URL options. 102 | * 103 | * @param array $options 104 | * The array of options. See \Drupal\Core\Url::fromUri() for details on what 105 | * it contains. 106 | * 107 | * @return $this 108 | */ 109 | public function setOptions($options) { 110 | $this->options = $options; 111 | return $this; 112 | } 113 | 114 | /** 115 | * Sets a specific option. 116 | * 117 | * See \Drupal\Core\Url::fromUri() for details on the options. 118 | * 119 | * @param string $name 120 | * The name of the option. 121 | * @param mixed $value 122 | * The option value. 123 | * 124 | * @return $this 125 | */ 126 | public function setOption($name, $value) { 127 | $this->options[$name] = $value; 128 | return $this; 129 | } 130 | 131 | /** 132 | * Returns the URI value for this Url object. 133 | * 134 | * @return string 135 | * A URI. 136 | */ 137 | public function getUri() { 138 | return $this->uri; 139 | } 140 | 141 | /** 142 | * Generates the string URL representation for this Url object. 143 | * 144 | * @return string 145 | * A string URL. 146 | */ 147 | public function __tostring() { 148 | return $this->uri; 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/DataTransformPlugin.php: -------------------------------------------------------------------------------- 1 | 12 | */ 13 | class DataTransformer 14 | { 15 | use ErrorHandlerTrait; 16 | 17 | protected static $processed = array(); 18 | 19 | protected $reservedKeys; 20 | protected $patternDataStore; 21 | protected $renderer; 22 | protected $hasRun; 23 | protected $currentPattern; 24 | 25 | public function __construct() 26 | { 27 | // TODO: Add an accessor function for $reservedKeys to the Data class? 28 | $this->reservedKeys = array("cacheBuster","link","patternSpecific","patternLabHead","patternLabFoot"); 29 | $this->patternDataStore = PatternData::get(); 30 | } 31 | 32 | public function run(Renderer $renderer) 33 | { 34 | if ($this->hasRun) { 35 | return; 36 | } 37 | $this->renderer = $renderer; 38 | // Process global data. 39 | DataTransformPlugin::writeInfo('processing global data'); 40 | $dataStore = $this->processData(Data::get()); 41 | Data::replaceStore($dataStore); 42 | // Process pattern specific data. 43 | DataTransformPlugin::writeInfo('processing pattern specific data'); 44 | foreach (array_keys($this->patternDataStore) as $pattern) { 45 | $this->currentPattern = $pattern; 46 | $this->processPattern($pattern); 47 | } 48 | $this->hasRun = true; 49 | DataTransformPlugin::writeInfo('processing done'); 50 | } 51 | 52 | protected function isProcessed($pattern) 53 | { 54 | return isset(self::$processed[$pattern]); 55 | } 56 | 57 | protected function setProcessed($pattern) 58 | { 59 | self::$processed[$pattern] = true; 60 | } 61 | 62 | protected function processPattern($pattern) 63 | { 64 | if ( 65 | $this->isProcessed($pattern) 66 | || !isset($this->patternDataStore[$pattern]) 67 | || $this->patternDataStore[$pattern]['category'] != 'pattern' 68 | ) { 69 | return; 70 | } 71 | $this->setProcessed($pattern); 72 | DataTransformPlugin::writeInfo("processing pattern '$pattern'"); 73 | $patternSpecificData = 74 | $this->processData(Data::getPatternSpecificData($pattern)); 75 | 76 | 77 | $dataStore = Data::get(); 78 | foreach (array_keys($patternSpecificData) as $key) { 79 | if (!isset($dataStore['patternSpecific'][$pattern]['data'][$key])) { 80 | // Value is default global data. 81 | if (isset($dataStore[$key]) && is_object($dataStore[$key])) { 82 | $patternSpecificData[$key] = clone $dataStore[$key]; 83 | } 84 | } 85 | } 86 | Data::initPattern($pattern); 87 | Data::setPatternData($pattern, $patternSpecificData); 88 | } 89 | 90 | protected function processData($data) 91 | { 92 | foreach (array_keys($data) as $key) { 93 | if (!in_array($key, $this->reservedKeys)) { 94 | $this->setErrorHandler(); 95 | $data = $this->processKey($data, $key); 96 | $this->restoreErrorHandler("error processing key '$key'"); 97 | } 98 | } 99 | 100 | return $data; 101 | } 102 | 103 | protected function processKey($data, $key) 104 | { 105 | $value = $data[$key]; 106 | if (is_array($value)) { 107 | foreach (array_keys($value) as $subKey) { 108 | $value = $this->processKey($value, $subKey); 109 | } 110 | if (isset($value['Attribute()']) && is_array($value['Attribute()'])) { 111 | $data[$key] = new Attribute($value['Attribute()']); 112 | DataTransformPlugin::writeInfo('created Attribute object', true); 113 | } 114 | elseif (isset($value['Url()']['url'])) { 115 | $options = isset($value['Url()']['options']) && is_array($value['Url()']['options']) ? $value['Url()']['options'] : []; 116 | $data[$key] = Url::fromUri($value['Url()']['url'], $options); 117 | DataTransformPlugin::writeInfo('created Url object', true); 118 | } 119 | elseif (isset($value['include()']) && is_array($value['include()']) && isset($value['include()']['pattern'])) { 120 | $pattern = $value['include()']['pattern']; 121 | if (is_string($pattern)) { 122 | if (isset($this->patternDataStore[$pattern])) { 123 | if (!isset($value['include()']['with']) || !is_array($value['include()']['with'])) { 124 | if (!isset($value['include()']['only'])) { 125 | $patternData = $this->getProcessedPatternSpecificData($pattern); 126 | } 127 | else { 128 | $patternData = array(); 129 | } 130 | } 131 | elseif (!isset($value['include()']['only'])) { 132 | $patternData = $this->getProcessedPatternSpecificData($pattern, $value['include()']['with']); 133 | } 134 | else { 135 | $patternData = $value['include()']['with']; 136 | } 137 | $data[$key] = $this->renderPattern($pattern, $patternData); 138 | DataTransformPlugin::writeInfo("included pattern '$pattern'", true); 139 | } 140 | else { 141 | DataTransformPlugin::writeWarning("could not find '$pattern' to include", DataTransformPlugin::isVerbose()); 142 | } 143 | } 144 | else { 145 | DataTransformPlugin::writeWarning('include() pattern key value was not a string', DataTransformPlugin::isVerbose()); 146 | } 147 | } 148 | elseif (isset($value['join()']) && is_array($value['join()'])) { 149 | $data[$key] = join($value['join()']); 150 | DataTransformPlugin::writeInfo("joined data under key '$key'", true); 151 | } 152 | else { 153 | $data[$key] = $value; 154 | } 155 | } 156 | elseif (is_string($value) && isset($this->patternDataStore[$value]) && $key !== 'pattern') { 157 | $data[$key] = $this->renderPattern($value, $this->getProcessedPatternSpecificData($value)); 158 | DataTransformPlugin::writeInfo("included pattern '$value'", true); 159 | } 160 | 161 | return $data; 162 | } 163 | 164 | public function getProcessedPatternSpecificData($pattern, $extraData = array()) 165 | { 166 | $this->processPattern($pattern); 167 | 168 | return Data::getPatternSpecificData($pattern, $extraData); 169 | } 170 | 171 | protected function renderPattern($pattern, $data) 172 | { 173 | $rendered = ''; 174 | if (isset($this->patternDataStore[$pattern]['patternRaw'])) { 175 | foreach (array_keys($data) as $key) { 176 | $data = $this->cloneObjects($data, $key); 177 | } 178 | $rendered = $this->renderer->render( 179 | $this->patternDataStore[$pattern]['patternRaw'], 180 | $data 181 | ); 182 | } 183 | 184 | return $rendered; 185 | } 186 | 187 | protected function cloneObjects($data, $key) 188 | { 189 | $value = $data[$key]; 190 | if (is_array($value)) { 191 | foreach (array_keys($value) as $subKey) { 192 | $value = $this->cloneObjects($value, $subKey); 193 | } 194 | $data[$key] = $value; 195 | } 196 | elseif (is_object($value)) { 197 | $data[$key] = clone $value; 198 | } 199 | 200 | return $data; 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/ErrorHandlerTrait.php: -------------------------------------------------------------------------------- 1 | 'E_WARNING', 9 | E_NOTICE => 'E_NOTICE', 10 | E_DEPRECATED => 'E_DEPRECATED', 11 | E_USER_DEPRECATED => 'E_USER_DEPRECATED', 12 | ]; 13 | 14 | protected $errno; 15 | protected $errstr; 16 | 17 | protected function errorHandler($errno, $errstr) 18 | { 19 | $this->errno = $errno; 20 | $this->errstr = $errstr; 21 | 22 | return TRUE; 23 | } 24 | 25 | protected function setErrorHandler() 26 | { 27 | $this->errno = null; 28 | $this->errstr = null; 29 | set_error_handler([$this, 'errorHandler']); 30 | } 31 | 32 | protected function restoreErrorHandler($errorMessage = null) 33 | { 34 | restore_error_handler(); 35 | if (isset($this->errno)) { 36 | $level = isset(self::$levels[$this->errno]) ? self::$levels[$this->errno] : $this->errno; 37 | if (isset($errorMessage)) { 38 | DataTransformPlugin::writeWarning($errorMessage); 39 | } 40 | DataTransformPlugin::writeWarning($this->errstr . ' (' . $level . ')', isset($errorMessage)); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/PatternLabListener.php: -------------------------------------------------------------------------------- 1 | 14 | */ 15 | class PatternLabListener extends Listener 16 | { 17 | /** 18 | * @var DataTransformer 19 | */ 20 | protected $dataTransformer; 21 | 22 | public function __construct() 23 | { 24 | if (DataTransformPlugin::isEnabled()) { 25 | $this->addListener('patternData.codeHelperStart', 'dataTransformer'); 26 | $this->addListener('twigPatternLoader.customize', 'addNodeVisitor', -99); 27 | DataTransformPlugin::writeInfo('listeners added'); 28 | } 29 | } 30 | 31 | public function dataTransformer() 32 | { 33 | $this->dataTransformer = new DataTransformer(); 34 | 35 | if (Config::getOption('patternExtension') !== 'twig') { 36 | $patternEngineBasePath = PatternEngine::getInstance()->getBasePath(); 37 | $patternLoaderClass = $patternEngineBasePath.'\Loaders\PatternLoader'; 38 | $patternLoader = new $patternLoaderClass([]); 39 | $this->dataTransformer->run(new Renderer($patternLoader)); 40 | } 41 | } 42 | 43 | public function addNodeVisitor() 44 | { 45 | $nodeVisitor = new PatternDataNodeVisitor($this->dataTransformer); 46 | 47 | $env = TwigUtil::getInstance(); 48 | if (DataTransformPlugin::isVerbose()) { 49 | $env = new TwigEnvironmentDecorator($env); 50 | } 51 | $env->addNodeVisitor($nodeVisitor); 52 | TwigUtil::setInstance($env); 53 | 54 | $this->dataTransformer->run(new Renderer($env)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/Renderer.php: -------------------------------------------------------------------------------- 1 | 9 | */ 10 | class Renderer 11 | { 12 | protected $renderer; 13 | 14 | public function __construct($renderer) 15 | { 16 | $this->renderer = $renderer; 17 | } 18 | 19 | public function render($pattern, $data = array()) 20 | { 21 | if ($this->renderer instanceof \Twig_Environment || $this->renderer instanceof TwigEnvironmentDecorator) { 22 | return $this->renderer->render($pattern, $data); 23 | } 24 | else { 25 | return $this->renderer->render(array( 26 | 'pattern' => $pattern, 27 | 'data' => $data, 28 | )); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/Twig/PatternDataEmbedNode.php: -------------------------------------------------------------------------------- 1 | hasNode('variables') 12 | ? $originalNode->getNode('variables') 13 | : null 14 | ; 15 | parent::__construct( 16 | $originalNode->getAttribute('filename'), 17 | $originalNode->getAttribute('index'), 18 | $variables, 19 | $originalNode->getAttribute('only'), 20 | $originalNode->getAttribute('ignore_missing'), 21 | $originalNode->getTemplateLine(), 22 | $originalNode->getNodeTag() 23 | ); 24 | 25 | $this->setData($data); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/Twig/PatternDataIncludeNode.php: -------------------------------------------------------------------------------- 1 | hasNode('variables') 12 | ? $originalNode->getNode('variables') 13 | : null 14 | ; 15 | parent::__construct( 16 | $originalNode->getNode('expr'), 17 | $variables, 18 | $originalNode->getAttribute('only'), 19 | $originalNode->getAttribute('ignore_missing'), 20 | $originalNode->getTemplateLine(), 21 | $originalNode->getNodeTag() 22 | ); 23 | 24 | $this->setData($data); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/Twig/PatternDataNodeTrait.php: -------------------------------------------------------------------------------- 1 | data .= $data; 17 | 18 | if (false !== $locale) { 19 | setlocale(LC_NUMERIC, $locale); 20 | } 21 | } elseif (null === $data) { 22 | $this->data .= 'null'; 23 | } elseif (is_bool($data)) { 24 | $this->data .= ($data ? 'true' : 'false'); 25 | } elseif (is_array($data)) { 26 | $this->data .= 'array('; 27 | $first = true; 28 | foreach ($data as $key => $v) { 29 | if (!$first) { 30 | $this->data .= ', '; 31 | } 32 | $first = false; 33 | $this->setData($key); 34 | $this->data .= ' => '; 35 | $this->setData($v); 36 | } 37 | $this->data .= ')'; 38 | } elseif (is_object($data)) { 39 | $this->data .= 'unserialize('; 40 | $this->data .= $this->string(serialize($data)); 41 | $this->data .= ')'; 42 | } else { 43 | $this->data .= $this->string($data); 44 | } 45 | } 46 | 47 | protected function string($value) 48 | { 49 | return sprintf('"%s"', addcslashes($value, "\0\t\"\$\\")); 50 | } 51 | 52 | protected function addTemplateArguments(\Twig_Compiler $compiler) 53 | { 54 | $variables = $this->hasNode('variables') 55 | ? $this->getNode('variables') 56 | : null 57 | ; 58 | if (null === $variables) { 59 | if (false === $this->getAttribute('only')) { 60 | $compiler 61 | ->raw('array_merge($context, ') 62 | ->raw($this->data) 63 | ->raw(')') 64 | ; 65 | } 66 | else { 67 | $compiler->raw('array()'); 68 | } 69 | } elseif (false === $this->getAttribute('only')) { 70 | $compiler 71 | ->raw('array_merge($context, ') 72 | ->raw($this->data) 73 | ->raw(', ') 74 | ->subcompile($variables) 75 | ->raw(')') 76 | ; 77 | } else { 78 | $compiler->subcompile($variables); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/Twig/PatternDataNodeVisitor.php: -------------------------------------------------------------------------------- 1 | dataTransformer = $dataTransformer; 17 | } 18 | 19 | protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) 20 | { 21 | return $node; 22 | } 23 | 24 | protected function doLeaveNode(\Twig_Node $node, \Twig_Environment $env) 25 | { 26 | if ($node instanceof \Twig_Node_Include) { 27 | if ($node->hasNode('expr') && $node->getNode('expr')->hasAttribute('value')) { 28 | $patternStoreKey = $node->getNode('expr')->getAttribute('value'); 29 | 30 | // Handle Twig namespace includes 31 | if ($patternStoreKey[0] == '@') { 32 | $patternStoreKey = ltrim($patternStoreKey, '@'); 33 | $lineageParts = explode('/', $patternStoreKey); 34 | $length = count($lineageParts); 35 | $patternType = $lineageParts[0]; 36 | 37 | $patternName = $lineageParts[$length - 1]; 38 | $patternName = ltrim($patternName, '_'); 39 | $patternName = preg_replace('/^[0-9\-]+/', '', $patternName); 40 | 41 | $patternNameStripped = explode('.twig', $patternName); 42 | 43 | if (count($patternNameStripped) > 1) { 44 | $patternName = $patternNameStripped[0]; 45 | } 46 | $patternName = str_replace('.', '-', $patternName); 47 | $patternStoreKey = $patternType . "-" . $patternName; 48 | } 49 | 50 | $data = $this->dataTransformer->getProcessedPatternSpecificData($patternStoreKey); 51 | if ($node instanceof \Twig_Node_Embed) { 52 | $dataNode = new PatternDataEmbedNode($node, $data); 53 | } 54 | else { 55 | $dataNode = new PatternDataIncludeNode($node, $data); 56 | } 57 | 58 | return $dataNode; 59 | } 60 | } 61 | 62 | return $node; 63 | } 64 | 65 | public function getPriority() 66 | { 67 | return 0; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/aleksip/DataTransformPlugin/Twig/TwigEnvironmentDecorator.php: -------------------------------------------------------------------------------- 1 | environment = $environment; 18 | } 19 | 20 | public function addGlobal($name, $value) 21 | { 22 | $this->environment->addGlobal($name, $value); 23 | } 24 | 25 | public function render($name, array $context = []) 26 | { 27 | $this->setErrorHandler(); 28 | $this->environment->render($name, $context); 29 | $this->restoreErrorHandler(); 30 | } 31 | 32 | public function __call($method, $args) 33 | { 34 | if ($method == 'errorHandler') { 35 | return $this->errorHandler(...$args); 36 | } 37 | else { 38 | return call_user_func_array([$this->environment, $method], $args); 39 | } 40 | } 41 | } 42 | --------------------------------------------------------------------------------