php-cs-fixer doesn't indent HTML inside PHP control structures - php

I'm trying to use php-cs-fixer with a WordPress project, which means I (unfortunately) have files with a mix of PHP and HTML. I'm using the #PSR12 ruleset.
I'm having trouble with getting HTML within PHP control structures to indent correctly. Take this example snippet:
<?php if (!empty($related_posts)) : ?>
<div class="module--related_posts alignfull has-2-columns has-hover-state slider-on-mobile">
<h3 class="has-text-align-center">Related <?= esc_html($title) ?></h3>
</div>
<?php endif ?>
php-cs-fixer reformats it to:
<?php if (!empty($related_posts)) : ?>
<div class="module--related_posts alignfull has-2-columns has-hover-state slider-on-mobile">
<h3 class="has-text-align-center">Related <?= esc_html($title) ?>
</h3>
</div>
<?php endif ?>
Note the closing h3 tag has been moved to a new line, and the first-level indent within the if statement body has been removed.
The h3 issue I can live with, as this is resolved if I put the opening tag on its own line:
<h3 class="has-text-align-center">
Related <?= esc_html($title) ?>
</h3>
...but the lack of indent within the if statement is going to do my head in. The same thing happens with for and while statements.
Is there a rule in php-cs-fixer that I've overlooked that will resolve this?

The Answer of keradus on the "PHP code does not align with html code" issue:
PHP CS Fixer was never written with supporting mixed html/php file.
Some fixers are supporting one php part and one html part inside single file, but not big mix of them, like in template files.
If we would like to support template files, we would need to not only detect and track concrete fixers, but also provide some big integration test (like we do for Sf ruleset) that it remains to work for most important rules.
Before that happen, I would not claim that we officially support html/php mixed-files.
And in another answer:
we do not aim to fix mixed file (PHP and HTML in single file)

Not really an answer but I ended up just switching to PHP_CodeSniffer to get around this.

Related

How to enable code folding with conditional blocks in PhpStorm (JetBrains)?

I was wondering if there is a way to enable PhpStorm (or any other JetBrains tool that deals with .phtml files) to recognize conditional blocks when collapsing units of code.
I have this example:
<div class="parent">
<?php if (condition) : ?>
<div class="div1">
<?php elseif (conditionTwo) : ?>
<div class="div2">
<?php endif; ?>
<!-- Conditional block ends here -->
</div>
<!-- Parent container ends here -->
</div>
PhpStorm (by default) allows me to collapse div2 (with the first </div>), therefore div1 will need to collapse with the last </div>, which is meant to be collapse with parent.
I have attempted to adjust settings, but with no success.
Microsoft's Visual Studio Code has the correct behavior:
As you can see, in VSCode you are not allowed to collapse on <div>'s that are inside the php if block.
Thanks for your time.
This can't be configured with given code sample. You can submit this to JetBrains tracker at https://youtrack.jetbrains.com/newIssue for developers to look into it & address in next IDE versions.
Really, the issue here is how you're writing the code. It would be cleaner (and remove the edge case of not having a final else if you did something like
<div class="<?= condition ? 'div1' : 'div2'; ?>">

Template inheritance and sections without Blade syntax

How to structure view hierarchy without using blade? What are the pure php counterparts of blade directives (i,e #section, #extend , etc)?
Perhaps, something similar to <?php extend('foo') ?>
In Phalcon framework, while it has its own template engine (Volt) all of its template engine is also available in pure PHP syntax.
Since Blade directives just compile to normal PHP, it is technically possible to use the view structuring features without actually using Blade. I don't think it's very pretty though, and I personally would think twice about this decision.
You can find all the PHP code, Blade is compiled to, in this class:
Illuminate\View\Compilers\BladeCompiler
Here are some of them:
#section('content')
<?php $__env->startSection('content'); ?>
#endsection
<?php $__env->stopSection(); ?>
#extends('layout')
This is a bit a tricky one. Usually Blade compiles it and then adds it to a footer variable which is printed at the bottom. So instead of putting it at the top (like you would with #extends) you have to place this at the end of your view:
<?php echo $__env->make('layout', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
#yield('content')
<?php echo $__env->yieldContent('content'); ?>
To put this in a pure PHP way you'll have to check out the storage/framework/cache/views and see what's happening there. Basically, is what Blade compiles to PHP code (instead of using # and with proper function calls).
One way I can think is:
In your template where you use yield:
<!-- template.php -->
<div class="container">
<!-- instead of using yield('container') -->
<?php echo "_yield:container"; ?>
</div>
In your file, instead of using section and stop
<!-- view.php -->
<!-- instead of using extend('template') -->
<?php $templatePath = 'template.php'; ?>
<?php $sections = []; ?>
<!-- instead of using section('container') -->
<?php $currentSectionName = 'container'; ob_start(); ?>
<p>This will be in my container div</p>
<!-- instead of using stop -->
<?php
// get the current html
$sections["_yield:".$currentSectionName] = ob_get_contents();
ob_end_clean();
ob_start();
require($templateName);
$template = ob_get_contents();
ob_end_clean();
echo str_replace($template,array_keys($sections),array_values($sections));
?>
Of course, this approach is simplistic at best. The code provided is not intended as a copy & paste solution, more like the concept.
Everything else is simple:
#foreach($arr as $k=>$v)
...
#endforeach
translates to
<?php foreach($arr as $k=>$v) : ?>
...
<?php endforeach; ?>
That's how it's exactly done by the BladeCompiler. The same is with if and while.
The pure PHP equivalent to Blade is to split your code in sections like header and footer (for example) and then use require in your page to blend those sections in the corresponding place.
<?php
require("template/header.php");
// Here goes the body code
require("template/footer.php");
?>
There is no pure PHP functions that i can think of, to extend a page from a main template, a you do using the yield directive.
Blade compiles into PHP every time and what it compiles is stored in to storage/framework/views/*
The following link is a list of all things blade can compile to, you should be able to extract some knowledge out of this:
https://github.com/illuminate/view/blob/master/Compilers/BladeCompiler.php
The general idea for most templating engine is that they structure your code like so:
if ($condition):
// do stuff
endif;
while ($condition):
// do stuff
endwhile;
foreach ($array as $key => $value):
// do stuff
endforeach;
For further reference, see https://secure.php.net/manual/en/control-structures.alternative-syntax.php
Neither of blade directives is a 'pure' PHP function. PHP functions cannot start with # and all blade directives do. In short, blade directives are shortcuts or synonyms to PHP built-in functions or control structures.
You are free to use any other template engine – it doesn't have to be Blade. Blade is built-in, but you are not locked to it. Just install a vendor package or make your own one, and return your HTML output with response, instead of using View facade.

Add <div> on a MediaWiki geshi syntax highlight extension

I use mediawiki to take note about the procedure that I follow, the source codes I write in mediawiki are highlighted with the expansion Genshi Syntax HighLight. I want to modify this expansion in mediawiki so it could be created a box above the source code in which it is written the programming language I used. I tried to see expansion sources in my mediawiki but I didn't find the segment in which is "sketch" the <div>. I also saw material about the creation of new expansion in mediawiki to understand how it runs, but I don't understand where the box is created.
I use syntax hightligher like this
some_code
and this is the result in html code generate from mediawiki
<div class="mw-geshi mw-code mw-content-ltr" dir="ltr">
<div class="bash source-bash">
<pre class="de1">
some_code
</pre>
</div>
</div>
I want to prepen the div to first div, like this
<div class='gsh-lang-label'>Language bash</div>
<div class="mw-geshi mw-code mw-content-ltr" dir="ltr">
<div class="bash source-bash">
<pre class="de1">
some_code
</pre>
</div>
</div>
Can you explain me if it is possible to do it and how can I face the problem?
I think ordinary jQuery will solve this problem. Something like:
$(".mw-geshi").each(function(){
$(this).before("<div class='gsh-lang-label'>" +
$(this).children().first().attr("class").split(' ')[0] +
"</div>")
})
Put this in [[MediaWiki:Common.js]], so this script will be run for every user.

How to make custom text use the Inline Translation tool in Magento Enterprise

I've created a piece of text in a Magento Template, and the inline translation tool is turned on and working fine, but when I visit the page with my custom text, it seems to ignore that it's translatable (no book icon and dotted red border).
So here's what I have (approx):
<div class="foo">
<?php echo $this->__('My custom Text'); ?>
</div>
Which renders fine, and if I edit the relevant CSV file, it changes appropriately.
Is there any way to "add" this to the translation tool's eyeline?
Thanks in advance!
OK, Managed to find the problem - so for anybody that wants to use the inline translation stuff, do:
<div class="foo">
<span>
<?php echo $this->__('My custom Text'); ?>
</span>
</div>
There's a list of allowed translatable inline tags on line #87 of app/code/core/Mage/Core/Model/Translate/Inline.php ("_allowedTagsSimple"). Enabling divs here is madness itself, but wrapping in spans should be generally quite safe.

What is this syntax and how to debug it?

I am currently working on moving an expression engine site from one server to another and i noticed one issue i am having a hardtime debugging. When i upload an logo image all seems fine but the index.php page that the logo is displayed on it has this code
{embed="shared/head"}
<body class="{if segment_1 == ''}home{if:else}{segment_1}{/if}">
<div id="page" class="container">
<div class="span-22 prepend-1 append-1 last">
{embed="shared/masthead"}
{if logo !=''}
<div class="news_item_logo">
{organization}
{if link}<img src="{logo}" width="130" alt="{title}" />{if:else}
<img src="{logo}" width="130" alt="{title}" />{/if}
{/organization}
</div><!-- /.news_item_logo -->
<ul>
<li><h3>{title}</h3></li>
<li>{pub_date}</li>
{organization}
<li>{if link}{/if}{exp:php_text_format type="lowercase"}{if url_text != ''}{url_text}{if:else}{name}{/if}{if link}{/exp:php_text_format}{/if}</li>
{/organization}
<li>{if file}PDF{/if}{if web_link !='' AND file !=''} | {/if}{if web_link}HTML{/if}</li>
</ul>
{if:else}
<ul class="no_logo">
<li><h3>{title}</h3></li>
My question is this, I see curly brackets {} around if statements and i want to know first what language it is and second is there a way to debug like php print_r() because the code always goes to the else with the no_logo class and i want to know what and how i can test these variables "segment1" and "logo" and "organization" and "url" How do and where do i inspect these variables
You can gain some info about the given variables and values in the template using the following within your index.php:
<?php
$EE = get_instance();
var_dump($this->EE->TMPL);
?>
Note that PHP must be enabled in templates for that to work (see PHP in Templates).
{embed="shared/head"} - include the template head from the template group shared
<body class="{if segment_1 == ''}home{if:else}{segment_1}{/if}">
if the URI segment (EE/CI works with segments eg site.com/segment1/segment2/xxx) is empty (you are on the home page (www.site.com), then add no body class.
else, the user is on a page (in EE this is a template group), so set the class to be the name of the template group.
site.com/about-us produces class="about-us" - handy for page specific styling.
{embed="shared/masthead"} - include masthead
and so on.
The rest are conditionals to check if the variables have values, and outputs them
I presume you're using EE2.0, I'm not sure what {organizaton} is specifically, but that style:
{organization} {foo} {/organization}
in code igniter at least, is generally the equivalent of a foreach or looping through a recordset:
foreach($organizations as $organization) { // do something }
This is written in Expression Engine's own templating language.
You would have to check the documentation to see whether there is any way to debug variables.
Possibly helpful links:
Quick Reference Chart
PHP in Templates

Categories