Zend_Validate good strategy to avoid repetition of code - zend-framework

I'm am currently building two custom validators that extends Zend_Validate_Abstract which are named respectively Lib_Validate_TimeAfter and Lib_Validate_TimeBetween. The names a pretty straight forward, the first one is used to test if a date/datetime/time comes after an other one and the second is used to test if a date/datetime/time comes between two other date/datetime/time.
Both of those validators would rely on the same method named _buildDate($value) which take a value in the form of a datestamp, a hourstamp(either hh:mm or hh:mm:ss), a timestamp or an ISO_8601 timestamp and convert it in a usable date format.
Since I dont want to repeat myself and copy/paste the method in both of my validator, I was looking for the best way to do it.
The avenues I am looking at right now would be to develop somekind of class helper that my validators would be able to use (kind of messy way of doing things since it add unessesary dependencies) or I could add an other layer of abstraction by building an other validator that validate date/datetime/time and then extend my two validators on that since I could share the method _buildDate($value), but then I don't think I would really need the validator.
So, what would be a good way (I am not really looking for the "Way of the gods" of doing thing) to structure that kind of code to avoid repetition (DRY)?

You might want to build one validator instead of two, where you can pass in a dateBefore, dateAfter which are both optional. If you pass only dateBefore, your $value will be valid if it is after that date, if you pass in both, it will have to be between them and if you pass in only dateAfter, the value will have to be before that date.
This would be flexible, clear, generic, less code and even cover one more case.

What about a class Lib_Validate_Common which extends Zend_Validate_Abstract which has your common method. And Lib_Validate_TimeAfter and Lib_Validate_TimeBetween extends Lib_Validate_Common .

Related

make play-json read the empty string as None for a type of Option[T]

I'm attempting to parse json from the GitHub API with play-json, and encountering a problem with the merge_commit_sha field on Pull Requests (incidentally, I know this field is deprecated, but don't want to discuss that in this parsing problem!). Unfortunately merge_commit_sha field comes back as the empty string in some cases:
"merge_commit_sha": ""
This is how the field is declared in my case class:
merge_commit_sha: Option[ObjectId],
I have an implicit Format[ObjectId], which does not tolerate the empty string, because that's not a valid value for a Git hash id. I'm also using a play-json macro-generated Read[PullRequest], which I'd like to keep on using, in preference to individually declaring reads for every single field on pull requests.
As I've declared the field to be an Option, I'd like "merge_commit_sha": "" to be read as the value None, but this is not what currently happens - a string is present, so the Format[ObjectId] is invoked, and returns a JsFailure.
One thing I tried was declaring an implicit Format[Option[ObjectId]] with the required behaviour, but it didn't seem to get used by the macro-generated Read[PullRequest].
You can define a custom Reads and Writes yourself.
Using Json.format[MyType] uses a Scala macro. You may be able to hook into that. Although, 'extending' a macro for this one case class just seems wrong.
Custom Reads and Writes might be a little 'boilerplate-like' and boring, but they have their upsides.
For example if your json has a bunch of new fields on it, you wont get a JsError when validating or transforming it to a case class. You only take what you need from the JSON and create objects. It also allows for a separation between your internal model and what you're consuming, which in some cases is preferred.
I hope this helps,
Rhys
EDIT
After using some other JSON libs I may have found what you are looking for.
I know the question was asking specifically after Play JSON.
If you're able to move away from Play JSON, Look at spray-json-shapeless specifically JsNullBehaviour and JsNullNotNone REF.

Can I use Eclipse templates to insert methods and also call them?

I'm doing some competitions on a website called topcoder.com where the objective is to solve algorithmic problems. I'm using Eclipse for this purpose, and I code in Java, it would be help me to have some predefined templates or macros that I can use for common coding tasks. For example I would like to write methods to be able to find the max value in and int[] array, or the longest sequence in an int[] array, and so on (there should be quite many of these). Note I can't write these methods as libraries because as part of the competition I need to submit everything in one file.
Therefore ideally, I would like to have some shortcut available to generate code both as a method and as a calling statement at once. Any ideas if this is possible?
Sure you can - I think that's a nifty way to auto-insert boilerplate or helper code. To the point of commenters, you probably want to group the code as a helper class, but the general idea sounds good to me:
You can see it listed in your available templates:
Then as you code your solution, you can Control+Space, type the first few characters of the name you gave your template, and you can preview it:
And then you can insert it. Be sure if you use a class structure to position it as an inner class:
Lastly - if you want to have a template inserts a call to method from a template, I think you would just use two templates. One like shown above (to print the helper code) and another that might look like this, which calls a util method and drops the cursor after it (or between the parentheses if you'd like, etc):
MyUtils.myUtilMethod1();${cursor}

How to create a scala class based on user input?

I have a use case where I need to create a class based on user input.
For example, the user input could be : "(Int,fieldname1) : (String,fieldname2) : .. etc"
Then a class has to be created as follows at runtime
Class Some
{
Int fieldname1
String fieldname2
..so..on..
}
Is this something that Scala supports? Any help is really appreciated.
Your scenario doesn't seem to make sense. It's not so much an issue of runtime instantiation (the JVM can certainly do this with reflection). Really, what you're asking is to dynamically generate a class, which is only useful if your code makes use of it later on. But how can your code make use of it later on if you don't know what it looks like? For example, how would your later code know which fields it could reference?
No, not really.
The idea of a class is to define a type that can be checked at compile time. You see, creating it at runtime would somewhat contradict that.
You might want to store the user input in a different way, e.g. a map.
What are you trying to achieve by creating a class at runtime?
I think this makes sense, as long as you are using your "data model" in a generic manner.
Will this approach work here? Depends.
If your data coming from a file that is read at runtime but available at compile time, then you're in luck and type-safety will be maintained. In fact, you will have two options.
Split your project into two:
In the first run, read the file and write the new source
programmatically (as Strings, or better, with Treehugger).
In the second run, compile your generated class with the rest of your project and use it normally.
If #1 is too "manual", then use Macro Annotations. The idea here is that the main sub-project's compile time follows the macro sub-project's runtime. Therefore, if we provide the main sub-project with an "empty" class, members can be added to it dynamically at compile time using data that the macro sees at runtime. - To get started, Modify the macro to read from a file in this example
Else, if you're data are truly only knowable at runtime, then #Rob Starling's suggestion may work for you as it did me. I'll share my attempt if you want to be a guinea pig. For debugging, I've got an App.scala in there that shows how to pass strings to a runtime class generator and access it at runtime with Java reflection, even define a Scala type alias with it. So the question is, will your new dynamic class serve as a type-parameter in Slick, or fail to, as it sometimes does with other libraries?

PropertyModel or Serializable object?

Which method is better?:
add(new Label("label", new PropertyModel<String>(cat, "name")));
or
add(new Label("label", cat.getName()));
I tried to find any information about comparison.. but couldn't find anything
How I understand the first method is for read/write logic and the second for read only logic, (if I am not right please write me). But for read only logic which better is?
They're functionally different.
The first one says: whenever this component is re-rendered, refresh the value. The second one says: display the value as it was at the time of creation.
Which one do you need? If you want a dynamically refreshing label, you have no choice, it's PropertyModel or CompoundPropertyModel (see later).
If you want it to stay the same, even if the underlying object changes, you can't use PropertyModels.
However, if you are absolutely sure that cat.getName() is never going to change, and therefore the two versions behave the same way, I personally wouldn't use PropertyModel for three reasons:
It breaks encapsulation: in the absence of a getter, it will try to access the private field itself.
As #Jesse pointed it out, it's "magic". If you refactor your class and rename your fields, your PropertyModel will break.
It's not easier to read or maintain. Granted, it's not that much harder either but why add any unnecessary complexity when you're not getting anything out of it? If you put cat.getName() there, you can "click through" in your IDE, your label will show up in a search for all invocations of the getName() method and so on.
If you have many components referring to fields of the same object, you can consider using CompoundPropertyModels, which, although still suffer from problems 1 and 2, make your code look a lot cleaner.
If you have three or fewer components like this though and you don't need a dynamic model, just use the modelless format.
This version is the better of the two options you gave:
add(new Label("label", new PropertyModel(cat, "name")));
It allows the value rendered on the page to update if the page is repainted later after the cat's name has changed.
The second option will only ever display the cat's name as it was at the time that the Label was created. It will never change if the cat's name changes.
There is something to be said for the dangers of using PropertyModel. It is "strings" programming. You compiler is not helping you verify the correctness of the property name "name". If you later refactor your code and change the name of the property to something like "firstName", then you will have to manually find all the places where you reference the old property name and change them by hand.

i18n in Symfony Forms

Is there any way I can use the format_number_choice function inside of a actions file. In fact I need to use it for a Form error message.
'max_size' => 'File is too large (maximum is %max_size% bytes).',
In English it's simply "bytes", but in other languages the syntax changes after a certain value (for example if the number is greater than 20 it's: "20 of bytes").
I can use parenthesis, of course, but if the framework offers support for doing this specific thing, why not to use it?!
The way it's currently implemented in the 1.4 branch, you can define only one translation per message using il18n XML files.
What you could do is create a custom validator which inherits the current validator (sfValidatorFile in your example) and does the size checking in the doClean method before calling its parent's method.
I suggest you take a look at the source to see how it works : sfValidatorFile
The correct way to handle number ranges for translation is explained here in the Definitive Guide. I won't reproduce it here as the documentation itself is clear and concise. Note however that the string is not extracted automatically by the i18n-extract task, so you need to add it manually - again, the documentation explains this.
So yes, you can use the format_number_choice() function inside an action - you just need to load the helper inside the action like this:
sfContext::getInstance()->getConfiguration()->loadHelpers('I18N');