I have a config file where I store all my strings for easy reference and to make translation easier - just in case I ever need to roll out my application into one of our international locations.
I would like to remove my hardcoded strings from both HTML and PHP code.
This site shows that IntelliJ IDEA is capable of highlighting hardcoded strings. However, I see no such option in my PhpStorm 2017.2 installation.
This is one example in HTML that I'd like to purge and replace with non-hardcoded strings:
<thead>
<tr>
<th class="text-center">#</th>
<th>Benutzername</th>
<th>Nachname</th>
<th>Vorname</th>
<th>E-Mail</th>
<th>Rollen</th>
<th></th>
</tr>
</thead>
However, PhpStorm does not highlight the hardcoded strings or suggests any fix. Same goes for PHP code.
If it's of any interest, here's how I usually retrieve strings from my config array.
/**
* Extract a string from the config file depending on its tag.
*
* #param string $tag The string to extract.
*
* #return mixed The string that was extracted. At least it should usually be a string, but it could also be
* something different, depending on the config.
*/
function get_string($tag)
{
// Check the config file first.
global $config;
$string = $config['strings'][$tag];
if (!isset($string)) {
// The faulty tag can be found in the logfile.
logfile("String Tag not found: " . $tag);
$string = $tag;
}
return $string;
}
I simply give the array index to the function and retrieve the string from the config array. If I ever need internationalisation, I can modify this function.
You can use 'cmd + f' and search for >[a-z0-9] which does a decent job finding any instances where an HTML tag ends and a string begins
#axiac provided a different point of view.
HTML is in itself basically full of hardcoded strings - tags et cetera.
PHP requires many strings to work. $_GET[], $_POST[] and array indices like my $config['strings'][$tag] are a few examples.
If PhpStorm were to highlight all of these strings, all of them would have to be excluded from inspection manually.
As #axiac said:
You can use the "Find in Files" command to find the strings in the PHP
scripts (search for ['"] and check "RegExp") but you'll probably be
overwhelmed by the big number of strings, many of them being array
keys or other strings (separators, SQL queries) that are part of the
code, not of the output.
Related
So I'm importing ExpressionEngine fields into a php array. I want to display one field, called {gearboxx_body}, unless that field has more then 300 characters, in which case I want to display a field called {article_blurb}. I'm pretty sure there isn't a way to do this just in ExpressionEngine fields and conditionals, so I tried some PHP, which I'm just starting to learn:
<?php
$info = array('{gearboxx_body}','{article_blurb}');
if(mb_strlen($info[0]) <= 300)
echo($info[0]);
}
else {
echo($info[1]);
}
?>
So that works well, but there's a problem. If the tag includes any apostrophes or quote marks, it ends the string and the page won't load. So what can I do about this? I've tried to replace the quote marks in the string, but I have to have loaded the string from the fields first, and as soon as I do that the page is already broken.
Hopefully that made sense. Any suggestions?
I would recommend you handle this in an EE plugin rather than in the template:
Faster to render (because you don't need the overhead of PHP in the templates)
More secure and reliable
Faster to develop once you get the basics of EE development down which is a useful life skill
All around best-practice
The plugin I have in mind takes three parameters:
body, blurb and character limit.
Let's say you call your plugin "Blurby". In the template you would just have this:
{exp:blurby body="{gearboxx_body}" blurb="{article_blurb}" char_limit="300"}
It variably returns either of your fields based on the logic you define in the plugin itself.
See plugin developer documentation.
Alternatively you could use the dreaded HEREDOC syntax to set variables before passing them into your array:
$body = <<<EOT
{gearboxx_body}
EOT;
$blurb = <<<EOT
{article_blurb}
EOT;
How to write code blocks using phpDocumentor while writing tutorials/extended documentation?
I have tried <programlisting>, it can generate the <code> tag , but it does not parse its contents.
<refentry id="{#id}">
<refnamediv>
<refname>Guide for MyApp</refname>
<refpurpose>To demonstrate ...</refpurpose>
</refnamediv>
<refsynopsisdiv>
<author>
My Name
<authorblurb>
{#link mail#mail.com My Name}
</authorblurb>
</author>
</refsynopsisdiv>
{#toc}
<refsect1 id="{#id intro}">
<title>User Guide for MyApp</title>
<para>
Some Description
</para>
<programlisting>
$some = 'code';
</programlisting>
</refsect1>
</refentry>
This is actually very easy once you know how. You just need to set the role attribute on the programlisting element.
<programlisting role="php">
$some = 'code';
</programlisting>
I couldn't find this documented anywhere, other than a brief mention in the release notes, but from looking at the code, there seem to be four roles that are supported:
php - adds PHP syntax highlighting to the content and includes a line number on every line.
tutorial - adds HTML syntax hightlighting to the content and includes a line number on every line.
xml - adds pre tags around the content, but otherwise no syntax hightlighting and no line numbers.
html - treats the content as raw HTML, so you can use whatever markup you like.
Any time you want to use angle brackets, though, you will need to escape those characters or wrap the content in a CDATA section. This even applies when you want to use raw HTML. If not, the parser will try and interpret the content as XML.
For example, a raw HTML sample would look something like this:
<programlisting role="html">
<![CDATA[
<b>This sentence will be bold.</b>
]]>
</programlisting>
Also note that all of this applies to the initial version of phpDocumentor. The new version (phpDocumentor 2) doesn't appear to support tutorials/extended documentation as far as I can tell.
I checked it and I think you can use javascriptMVC documentation tool. I thik Documentation Tool.
and a demo of it is here. and I suggest you to try this.(-:
here is an output of documentJs of javascriptMVC which is /i think the thing you want. or at least I hope.(-:
and about phpDocumentor As I said I need some explains to get what you mean but for now please check these. link1.
link2 . (if the following is the thing you want).
/** #type int This is a counter. */
$int = 0;
// there should be no docblock here
$int++;
Or:
/**
* This class acts as an example on where to position a DocBlock.
*/
class Foo
{
/** #type string|null Should contain a description if available */
protected $description = null;
/**
* This method sets a description.
*
* #param string $description A text with a maximum of 80 characters.
*
* #return void
*/
public function setDescription($description)
{
// there should be no docblock here
$this->description = $description;
}
}
Another example is to document the variable in a foreach explicitly; many IDEs use this information to help you with auto-completion:
/** #type \Sqlite3 $sqlite */
foreach($connections as $sqlite) {
// there should be no docblock here
$sqlite->open('/my/database/path');
<...>
}
You can user zend studio tool which can generate selected project documentation automatically
I'm implementing a php interface to process a .php file containing a bunch of define sentences defining constants with text values to translate by somebody.
The input is parsed sentence by sentence and shown in the interface to the translator who will input the translation in a html textarea and send it to the server
By the end of the process an output file would be generated, identical to the input .php file, only with the define values translated.
E.g. processing an input file 'eng.php' like this:
<?php
define ("SENTENCE_1", "A sentence to translate");
?>
would give the translated output file 'spa.php' like this:
<?php
define ("SENTENCE_1", "The same sentence translated to spanish");
?>
For this I would like to know:
What is the best way to parse the input file to get the constant names and values in an array? (Something like $var[0]['name'] would be "SENTENCE_1" and $var[0]['value'] would be "A sentence to translate")
Would it be possible to get the translation from google translator shown in the input textarea as a suggestion to edit for the person who is translating it? How? (I read google translator api v1 is no longer available and v2 is only available as a paid service. Are there any free alternatives?)
http://php.net/manual/es/function.get-defined-constants.php
What about that?
get_defined_constants doesn't give you exactly the structure you asked for, but it should be sufficient.
define('MY_CONSTANT', 'something');
define('MY_CONSTANT_2', 'another');
$constants = get_defined_constants(true);
$constants = $constants['user'];
print_r($constants);
/**
* array(
* 'MY_CONSTANT' => 'something',
* 'MY_CONSTANT_2' => 'another'
* )
*/
Note that this will be all constants defined in the current scope, which in PHP is gonna be anything defined this request.
Use get_defined_constants() to get the list of all the defined constants.
To get userdefined constant specially
$allconstants = get_defined_constants(true);
print_r($allconstants['user']);
In case anybody needs to read constants' names and values defined in a given .php file into an array of variables without actually defining those constants (E.g. if some different constant with the same name was previously defined, thus giving an error when processing the file with include or require), here is how I did it (Warning: I haven't had any trouble yet, but it's not thoroughly tested, so it can be buggy).
if (file_exists($filename)){
$outf=fopen($filename,'r');
while (($line=fgets($outf))!==false){
if (strpos($line, 'define')!==false){
$parts=explode("\"",implode("\"",explode("'",implode("\\q",explode("\\\"",implode("\\s",explode("\\'",$line)))))));
$name=implode("\\'",explode("\\s",implode("\\\"",explode("\\q",$parts[1]))));
$value=implode("\\'",explode("\\s",implode("\\\"",explode("\\q",$parts[3]))));
$outconstants[$name]=$value;
}
}
}
You can see I assume there's no more than 1 define sentence per line, and that the names and values of the constants are specified as string values using PHP notation (between single (') or double (") quotes.)
Also, escaped quotes (\" or \') are temporarily escaped as \q (\") or \s (\') instead, to properly match the non-escaped ones, and then escaped back as usual once what's in between the non escaped ones is assigned to $name and $value.
The google api problem was solved using microsoft translation api instead (free up to 2.000.000 chars/month): http://msdn.microsoft.com/en-us/library/ff512421.aspx#phpexample
I am trying to write a PHPDoc description and as soon as I type a dot (.) it just cuts the rest of the description in the code assistant. For example,
/**
* A boolean value indicating whether code assitant worked with dots in PHPDoc.
* As you can see, it did not work!
* #var bool
*/
public $var = false;
I only see the first line in the code assistant. How would I solve this problem?
I haven't had any luck using the Short Description and Long Description in Eclipse (Helios) - even though it should be supported.
An option if you want to increase the length of your short description is to use the <br> tag. As long as you don't include a period in your short description, you can span it over multiple lines. You can even use other tags to add a bullet list if you like.
/**
* Function to take a 10 digit phone number and<br>
* return it in North American standard format of:<br>
* <ul><li>(123) 456-7890</li></ul>
*
* #param int $phone <ul><li>up to 10 digit int for the phone number</li></ul>
* #return string <ul><li>formatted phone number</li></ul>
*/
Eclipse Helios supports most (if not all) of the DocBlock format tags listed on this web page.
phpDocumentor Tutorial: DocBlock Description Details
However, not all these tags work in all instances, and there are definitely examples in other sections of this page that do NOT work. But using these techniques can definitely make your phpDoc blocks look better.
It is likely that the code assistant logic expects that docblock descriptions exist in the "one sentence summary description, followed by a longer detailed description", and most likely only shows the summary description in popups. In Eclipse, you can tab into the code assistant popup, and the information in there expands to show everything (via scrollbars).
UPDATE:
Testing KingCrunch's exact layout of (short description to a period, blank like, additional description with/without a period, blank line, tags) in Eclipse PDT on Helios shows that the period in the first sentence does indeed prevent the popup from showing any of the description beyond the period. I even moved the secondary portion onto the same line with the first portion, and everything beyond the period still does not appear. Change it to a comma, and everything up to the next period will then appear. Well, unless there's a blank line between the comma'd line and the next line... in that case, the blank line has the same effect as a period would, blocking everything after it. I see no issue with the tags being seen and interpreted, regardless of whether or not the description pieces are visible.
I believe, therefore, that Eclipse is indeed ignoring all description beyond the first period and/or blank line that it encounters. I'm unaware of a way to disable this behavior.
ashnazg is almost right. Usually there is the "short summary". You have no empty line after that, so it assumes, that the whole block (including the tags) belongs to the summary and are cut down after the first full stop (because its a short summary ;))
Newlines after the short summary and before the tags should work.
/**
* A boolean value indicating whether code assitant worked with dots in PHPDoc.
*
* Should work ;)
*
* #var bool
*/
public $var = false;
I've found that you can display multiple sentences if you put an HTML-encoded space character (" ") after the period. For example:
/**
* Sentence One. Sentence Two.
*/
However, if you want to include line breaks in your PHPDoc comment to make it easier to read from the source code, it will only allow up to three lines. If you include any more, only the first line will be displayed. This makes complete sense because you will never ever need more than three lines. For example:
/**
* Line one.
* Line two. Another line two sentence.
* Line three.
* This fourth line being here will prevent lines 2, 3, and 4, from being displayed.
*/
Thanks for posting this question. I've been wondering if I installed PDE wrong or something.
I know this has been asked (Python Markdown nl2br extension, etc) but none of those answers is doing it for me.
I would like to render markdown so that linebreaks occuring within a <p> element will be rendered as <br>. Example: they type
Here is line one.
And line two.
New paragraph.
should render as
<p>Here is line one.<br>And line two.</p>
<p>New paragraph.</p>
I know that if you want that, you should type two spaces at the end of the line you want to <br>. I am trying to make it so my users don't have to do that, but rather, enter text as though they were using a typewriter (for those who know what that is). One hard return, new line; two hard returns, new paragraph.
I've been working with https://parsedown.org/ and have also experimented with https://commonmark.thephpleague.com; also the Python markdown module with nl2br extension (tried their example verbatim, did not work for me). Whatever I do, I end up with either too many or not enough linebreaks, depending.
I have tried what I thought would be clever and elegant: style my markdown's <p> with white-space: "pre" (also tried pre-line). That works, unless the user has done it "right" with two spaces, in which case you get the unwanted double <br> effect.
Also tried nl2br($markdown) with likewise unreliable results.
I want non-technical users to be able to use some basic formatting as easily as possible, and markdown seems just the thing, but for this detail. I don't want to write a CMS just to work around this. For example, I've thought of adding a boolean markdown property on the entity and letting them choose, yadda yadda... don't wanna go there. I've thought of doing some string-replacement or regexp magic, either at database-write time or just before rendering. But again, hoping to avoid getting too complicated. (To make it a little more challenging, I will also have to import a few thousand legacy records that are non-markdown, and potentially deal with issues around old ones versus new.)
Maybe I'm overlooking a simple, sane way out. Any thoughts as to the best strategy?
Update: by popular demand, code examples of what does not work. It's a Zend MVC application that involves Doctrine entities I call MOTD and MOTW (Message Of The Day and Message Of The Week, respectively); these have a string property called content. Generically I think of these entities as Notes and they implement a NoteInterface. When I retrieve these from the database (via a NotesService class that internally uses a custom Doctrine repository class), it's time to render the content as markdown before the controller assigns it to the view:
// from NotesService.php
use Parsedown;
// stuff omitted...
/**
* gets MOT(D|W) by date
*
* #param DateTime $date
* #param string $type
* #param boolean $render_markdown
* #return NoteInterface|null
*/
public function getNoteByDate(DateTime $date, string $type, bool $render_markdown = true) :? NoteInterface
{
$entity = $this->getRepository()->findByDate($date,$type);
if ($entity && $render_markdown) {
$content = $entity->getContent();
$entity->setContent($this->parsedown($content));
}
return $entity;
}
The point of the boolean $render_markdown is for when we want raw markdown, i.e., when it's going to populate a textarea element of a form.
And the parsedown() method, quite simply:
public function parsedown(string $content) : string
{
if (! $this->parseDown) {
$this->parseDown = new Parsedown();
}
// nope...
// return nl2br($this->parseDown->text($content));
return $this->parseDown->text($content);
}
Inside a viewscript, I just go, e.g.,
if ($this->notes['motd']):
// echo nl2br($this->notes['motd']->getContent());
echo $this->notes['motd']->getContent();
else:
?><p class="font-italic no-note">no MOTD for this date</p><?php
endif;
Now, if in the editing form they input this as content:
here is a line
and here is another
now, new paragraph.
and then we save it in the database, when you select it back out and run it through $parsedown->text($content), you get this HTML:
<p>here is a line
and here is another</p>
<p>now, new paragraph.</p>
Please note, the example input above does not have any space characters preceding the linebreaks. When you do type two spaces before the linebreaks, yeah, it works great. But I don't think my users want to think about that. So using nl2br() helps, except when it results in too many consecutive <br>s in the HTML.
My latest thinking is, use a CSS solution and an input filter that strips <space><space> at the end of lines. When it works, I'll add the story to my memoir. :-)
There may be some more desirable way to achieve this, but finally I decided to
(1) filter the input (at create|update time) with regexp pattern substition to remove trailing ' ' (two consecutive space characters) from lines. I happen to be using ZendFramework's Zend\Filter\PregReplace but it's a de facto wrapper for preg_replace('/( {2,})(\R)/m',$2).
(2) Use CSS to make newlines act like <br> when I display these entities, e.g.,
#motd .card-body p { white-space: pre-line }
Seems to be working for me.