Convert Line breaks to html break for all field getters in Symfony project - symfony1

I am working on a Symfony project and I currently have this:
<?php echo preg_replace('/\n/','<br />', $review->getComments()); ?>
and would very much like to be able to make all getters add html line breaks so i don't have to pepper my code with preg_replace. the $object->getFieldname methods are work automatically so I am looking to extend this somewhere to globally add a new method. What is the best approach here?

Seems like everyone forgot about nl2br() which is a function that does exactly that in PHP.
nl2br($review->getComments());
EDIT: At the time of this writing, everyone else uses preg_replace().

I think the best idea would be to add a getCommentsHtml() method onto your review object, which does something like:
return preg_replace('/\n/','<br />', $this->getComments());
Then you can use $review->getCommentsHtml() to format them using HTML. Also as Charlie mentioned, maybe str_replace would be better to use, as using a regular expression to change \n's into <br />'s may be a little bit of overkill :)
So if you don't want to have your code littered with replaces like this, I think putting a helper method on the classes that you'd like to format nicely would be the best way to go :)

How about:
str_replace("\n",'<br />', $review->getComments());

Related

RESTFUL formatting of URLs

Simple question, in terms of best practice is it better to format my URL like this:
http://www.example.com/search?query=hello&page=1
or like this:
http://www.example.com/search/hello/page/1
Can you provide a valid reason for your choice please.
First one fits the situation where you want to "filter" your result if it gets a little too complicated, like this example:
cars.com/audi/sedan/a/4/black/manual.....
this is gonna take so long and complicated and result will be nightmare, but this would work better:
cars.com/mercedes/amg?color=white&transmission=manual
2nd way is just like thinking it of a 'folder'ed structure:
socialmedia.com/shares/1/comments/1/page/2
I am pretty sure you get the idea.
p.s. if you will provide your API to a brand new clients, who don't know anything about it, then first one is also more understandable but, i suggest you also have a API documentation which describes the parameters and the relevant poasible other calls as well. in this way your url formatting will be clearer and clients will not struggle to solve parameters in the url.
The first way is not only functional, but lets a human understand what the name/value pairs are. Sure you could go into configuration and string manipulation and make your URL look like the second example and still function, but from a readability pov and ease of function, the first one is best.

How the url should be stored in records?

I have a question.
I have comment model, in which it has body column that users can type anything in there.
obviously user might type the url link to other website.
In my guess, I think it should be replaced with < a href > tag when it is being saved.
Is there any good gem or something to handle this kind of thing?
If you don't want to use a full-blown markdown parser (Redcarpet), use Rinku. It's super fast and safe. Do not use any regex based solutions as you would most likely open yourself to security risks.
text = "Hello! Check this out: https://github.com/vmg/rinku"
Rinku.auto_link(text, mode=:all, link_attr=nil, skip_tags=nil)
Produces:
=> "Hello! Check this out: https://github.com/vmg/rinku"
Preserving for posterity's sake, but I feel it's important to note that this is NOT a secure way to solve the problem. Unless you want to figure out all the security implications for yourself, don't follow this advice. Jiří Pospíšil's answer is better. =D
You don't really need a gem to do that (I personally try to avoid gems for something so simple). Write a regular expression that is reasonably reliable for your purposes, and then use something like
input.gsub(regex, 'some text')
to convert the links into their html equivalent. Note that you'll need to use raw to display the results of this, otherwise rails will escape the output for you. This also means users will be able to put other arbitrary markup in, unless you escape it as it goes into the database. Make sure you do that.
Alternately, you could do the same thing as you display it, with slightly different considerations/steps necessary.

How to make ASP.NET MVC create lowercase urls (action links)?

I know this question has been asked many times. But people suggest creating custom derived route classes, or writing lowercase everywhere in code (for action links) which is a really dirty way (what if I just decide to make'em all Pascal Cased again? changing hundreds of links?), or they suggest to create HTML helpers to do that (which is not a bad answer). But isn't there a more simple way? I mean something like setting some configuration in web.config file, or using an HttpModule or something else which is both simple, and centralized?
Apart from the options you have already listed, I can think of no other way of producing this result.
In short, the URL needs to be processed by 'something', be it .ToLower(), a Helper Method or HTTPModule.
In most of our applications, we use a Global Static method that performs actions on the desired URI and returns the result.
The following will allow that.. http://mvccoderouting.codeplex.com/ - and much more besides.

Sanitize output in Rails

What is the best solution to sanitize output HTML in Rails (to avoid XSS attacks)?
I have two options: white_list plugin or sanitize method from Sanitize Helper http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html . For me until today the white_list plugin worked better and in the past, Sanitize was very buggy, but as part of the Core, probably it will be under development and be supported for a while.
I recommend http://code.google.com/p/xssterminate/.
I think the h helper method will work here:
<%= h #user.profile %>
This will escape angle brackets and therefore neutralize any embedded JavaScript. Of course this will also eliminate any formatting your users might use.
If you want formatting, maybe look at markdown.
Personally I think it's not a small decision to accept any HTML entry in any web app. You can test for white/blacklisted tags as much as you like, but unless you're testing for correct nesting, someone could enter a series of closing tags, for example
</td></tr></span></div>
and really mess with your layout.
I'd usually give people something like Textile to enter their markup, since I'd rather spend my time working on business logic than HTML parsing.
Of course, if this text entry is more fundamental to your app (as for example it is for stackoverflow) then you probably should give more attention to hand-rolling your own.

What is the opposite of 'parse'? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 8 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I have a function, parseQuery, that parses a SQL query into an abstract representation of that query.
I'm about to write a function that takes an abstract representation of a query and returns a SQL query string.
What should I call the second function?
I think the verb you want is 'compose'.
The opposite of parse is serialize
In compiler terminology, the opposite is "unparse". Specifically, parsing turns a stream of tokens into abstract syntax trees, while unparsing turns abstract syntax trees into a stream of tokens.
Compose? When parsing a query you break it into its constituent parts (tokens, etc.), the reverse would be composing the parts into a string query.
To complement your existing naming, composeQuery looks best.
But in the general case, the opposite of parse is ǝsɹɐd
I would use one of these:
ToString()
ToSQL()
Render()
I think "serialize" is probably the word you want. It means to produce a textual representation of data that can be exported (and imported) from the program.
The antonym of 'analyze' is 'synthesize'.
ToQueryString()
Definitely Render.
I would call it constructQuery.
generate or emit, possibly.
Just to add some stuff.
Surely parse is a two way word.
You can parse an abstract into a query.
You can parse a query into an abstract.
The question should be, what do you name the latter part of the method, and because in this instance you're parsing an abstract to make a query you'd call it parseAbstract.
To answer the question, parsing has no opposite.
generateQuery, possibly? createQuery?
Take your pick
Generate
Dump
Serialize
Emit
They each have slightly different connotations.
Maybe prettyPrintQuery?
compose, construct, generate, render,condense, reduce, toSQL, toString depending on the nature of the class and its related operators
A traditional compiler has two parts: a parser and a code generator.
So you could call it "Generate". Of course, it's a little bit different here because the compiler isn't writing source code. (unless it's a precompiler).
Possibly Format(). or ToSQL() in your instance?
unParse()? Just kidding, I would go with toQueryString()
flatten?
The parsed query object perhaps represents a condition hierarchy, which you are "flattening" back into a 1 dimensional string.
But given that you're going from object to string, really just use toString or toSQL() or something like that. Besides, if you designed it well and are using the right app, you can rename it later and just stick stuff in the comments on what it does.
I'd say serialize and deserialize, instead of parse and ...
I would go for ToString(), since you can usually chain-nest them (opposite functions, that let you pass from Class1 to Class2 and vice-versa)
DateTime.Parse( DateTime.Parse( myDate.ToString() ).ToString() );
Serialize() looks like a nice choice, but it already has an opposite in Deserialize().
In your specific scenario, as other pointed out, ToSql() is another good choice.
I'd use render
> a = 'html': { 'head': {'title': 'My Page'}, 'body': { 'h1': 'Hello World', 'p': 'This is a Paragraph' } }
> b = render(a)
> console.log(b)
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello World</h1>
<p>This is a Paragraph</p>
</body>
</html>
Which is IMHO, the opposite to parse()
> c = parse(b)
{ 'html': {
'head': {
'title': 'My Page'
}
'body': {
'h1': 'Hello World',
'p': 'This is a Paragraph'
}
}
+1 for Generate, but tack on what you're generating, i.e. GenerateSQL()
I voted for 'compose' but if you don't like that I would also suggest 'build'
What about asSQL() or even more asQuery()?
INHO Serialize, synthesize are good options. Also, as you have named parseQuery, i will go with codeQuery
I usually use "parse" as a conversion method and, therefore, i can't find a opposite word for "convert". (you can't "deconvert" something, as "unconvert" is a type of conversion itself).
thinking this way, the best solution (for me) is having two "parse" methods that receive different arguments. Example (Java):
public class FooBarParser{
public Foo parse(Bar bar);
public Bar parse(Foo foo);
}
deparse
Deparse is to parse, as:
decompile is to compile
decompose is to compose
deserialize is to serialize
degroovy is to groovy :) ;)
Parsing / deparsing is not change of structure, but conversion. Precise conversion between equivalent text and abstract-syntax-tree formats, maintaining all relationships & structure.
"Compose" means change of structure, so is not quite right. It suggests combining from separate independent parts (usually for the first time). Just as "decompose" suggests splitting into independent parts. They change form, not just format.
A quick search show's the term's used within:
Perl: http://perldoc.perl.org/B/Deparse.html
R: http://www.hep.by/gnu/r-patched/r-lang/R-lang_98.html
Common Lisp: http://www.clisp.org/impnotes/dffi.html#c-type-parse
PostgreSQL: http://doxygen.postgresql.org/deparse_8c.html
Eclipse: http://www.eclipse.org/forums/index.php/t/201883/
Unix Korn Shell: http://www.sourcecodebrowser.com/ksh/93tplus-p/deparse_8c.html

Resources