When writing PHP in Netbeans, as long as I provide my functions and classes with "docblox", Netbeans will show what parameters a function expects, what it will return, and a short description whenever I go to call it somewhere else. There is also the benefit of using it for automatically generated API documentation with a tool such as PHPDocumentor2. Is there any kind of equivalent in R? Currently I'm developing in RStudio.
Example of a docblox in PHP:
/**
* This is the description of some function
*
* #param string $foo A foo string
* #return string Foo string in all caps
*/
function cap_foo($foo) { return strtoupper($foo); }
Is docblox the commented part? If so, check roxygen2
Related
I got a lot of products, and it can be filter with a lot of different parameters.
So user input search parameter in a form, and then the list is filter by those parameters.
I have try to create a route like this :
/**
* Display a list of product
* #Route("/product/list/{name}/{price_min}/{price_max}/{publish_date}/{supplier_code}", name="product_list")
*/
public function listProduct(){
// ... Check parameters format and then escape special caracters
// ... Display product logic
return $this->render('Product/product_list.html.twig', $array_params_view);
}
I know you can provide optional parameter, but this solution looks really bad to me...
I think there might be another solution.
I have think to use the Request instead of a lot of parameter, but if I do so, I loose the fonctionality of nice and easily readable URL, and maybe it'll be more difficult to manage routing.
I don't know what is the best solution for search functionnality.
If you use route for search into your list, I think you need to read this : link
Query String is a better way for search.
// the query string is '?foo=bar'
$request->query->get('foo');
// returns 'bar'
/**
* Display a list of product
*
* #Route("/list/", name="product_list")
*
* #param Request $request
*
*/
public function listProduct(Request $request)
{
$name = $request->query->get('name');
$price_min = $request->query->get('price_min');
$price_max = $request->query->get('price_max');
$publish_date = $request->query->get('publish_date');
$supplier_code = $request->query->get('supplier_code');
$list_products = $this->getListProducts($name,$price_min,$price_max,$publish_date,$supplier_code);
//Next code
......
}
You would only have to control within the getListProducts function
or whatever you call it, that the arguments can arrive as null
I'm using #testdox annotation in PHPUnit 8 to set the description for my tests.
This works fine, but I'd like to be able to set the description dynamically. A method like this would be nice:
$this->setTestDoxDescription("My super test routine for date: ".$mydate->format('Y-m-d');
I have tests that check the results of various date-related functions. Many of the tests are relative to today's date, so the input date values are not fixed and are generated dynamically. I would like to be able to print the date values in the description.
I just discovered the setName() method in TestCase and it seems to do mostly what I want:
$this->setName("My super test routine for date: ".$mydate->format('Y-m-d');
However, there is some kind of parsing and it is splitting my dates on - chars and adding extra spaces. For example, 2020-04-04 is changed to 2020- 04- 04. But if I use #testdox 2020-04-04 it does not split things. It is only a problem when I use setName(). Not a big deal, but kind of annoying.
I've solved my problem for now, but maybe someone can recommend a better way.
You can put variable names into the #testdox string, the variables that are being returned from the #dataprovider (given as the method parameters).
An example from phpunit's own tests...
/**
* #testdox Valid regex $pattern on $subject returns $return
* #dataProvider validRegexpProvider
*
* ....
*/
public function testValidRegex($pattern, $subject, $return): void
I've just added it to my own tests and one dataprovider/testdox output example is:
#testdox displayNumber formats $input as '$expectedLong' & '$expectedShort'
public function testNumber($input, $expectedLong, $expectedShort): void {}
✔ displayNumber formats 1781234 as '1,781,234' & '1.8M'
MockBuilder::setMethods() method got deprecated in 8.3, but examples in the documentation still use it, and I can't find a definitive migration guide anywhere. Does one exist?
Out of respect for your time potentially spent writing an answer: answers boiling down to "just keep using setMethods(), it still works" will not be accepted.
setMethods() has been deprecated as of this PR
At this moment of the time documentation are outdated but I guess they will be fixed in no time. To answer your question about setMethods it has been replaced with two new functions
onlyMethods
/**
* Specifies the subset of methods to mock, requiring each to exist in the class
*
* #param string[] $methods
*
* #throws RuntimeException
*/
public function onlyMethods(array $methods): self
{...}
addMethods
/**
* Specifies methods that don't exist in the class which you want to mock
*
* #param string[] $methods
*
* #throws RuntimeException
*/
public function addMethods(array $methods): self
{...}
Example
Old Code might have looked like this
$merchant = $this->getMockBuilder('\Fake\FakeMerchant')
->setMethods(['getLegalEntity'])
->getMock();
which should be now like this
$merchant = $this->getMockBuilder('\Fake\FakeMerchant')
->addMethods(['getLegalEntity'])
->getMock();
Extra Information
I didn't find the definitive migration guide but since I recently
had to migrate from old phpunit 4.x to new phpunit 8.4 here are the tips that you can follow.
PHPUnit_Framework_TestCase has been replaced with PHPUnit\Framework\TestCase
PHPUnit_Framework_MockObject_MockObject has been replaced with PHPUnit\Framework\MockObject\MockObject
->getMock has been removed. So the alternative is either ->createMock(), createPartialMock or ->getMockBuilder()->getMock()
Functions like setUp setUpBeforeClass, tearDown, etc now need to define ::void return type
mockObject->setMethods is deprecated and should be replaced with onlyMethod for method that already exists and addMethods for methods that does exists on the class
#expectedException from docblock is deprecated and $this->setExpectedException has been removed
this is my first time of developing with translation service.
I implemented it, seems to be working, but how can I test other languages?
Can I change the default language in my symfony project?
Or can I change the language transfered to my project via the browser?
(I only found the settings to change browser GUI language)
Regards
n00n
you can also do it inside controller using the session like this:
/**
* Switch language
*
* #Route("/switchLanguage/{locale}/", name="switch_language")
*
* #param Request $request
* #param string $locale
*
* #return RedirectResponse
*/
public function switchLanguageAction(Request $request, $locale): RedirectResponse
{
$request->attributes->set('_locale', null);
$this->get('session')->set('_locale', $locale);
return $this->redirect($request->headers->get('referer'));
}
Yes of course you can there is few approach for translation.
If you want save your project translation data in your database you must create entities for data translation and after that you can use global sql filter for selecting data each language.
And you can read about Symfony Translation Component.
For changing project language you can write listener.
like this
public function onKernelRequest(GetResponseEvent $event)
{
/** Set language parameter*/
$lang = $event->getRequest()->query->get('lang', 'en'); //this is optional you can write another code for getting language.
$event->getRequest()->setLocale($lang);
}
This example if you want to set each request language.
Read symfony translation component documentation there are more useful things.
Is there anything in the Symfony annotations modules that allow me to use them for other uses?
I know for #Route and #Method you need to extend existing libraries, so its just not that easy i'm guessing.
Currently, i'm working with the JS History API, and would LOVE to put the popState data for my JS files in the annotations. So they are already available when the routing generates the URL.
Q Doesn't this makes sense to have a, HTML5 annotated title, or some attribute here? It would be great to have the ability to define this data, as annotated, right next to the already existing route name and stuff.
Q Is there anybody that has tweaked with the annotations before?
I wanted to clarify my intentions here as I think I left out some crucial details (the mention of History API) for understanding my use case.
There is a few SPA front ends that have been integrated through a front-end bundle, and this connected via AJAX calls to a backend bundle which was a straight RESTful API, with the addition of a very fun-to-develop PHP API class I made that intereprets and processes (routes) the AJAX in a fashion that directly executes other PHP class controller `methods.
I use a lot of ajax for this Symfony 2 app (fosjsrouter) to handle routing. So instead of URLs triggering the routes and actions, the SPA click event fires off AJAX to the back end router, with a large JSON payload, not limited to PHP control parameter's (class/method/var names), and data sets.
OK, so getting back on track; Given the above scenario; In the JS class object end of the router, inside this I thought it was the best place to add some JS History API functionality to it, (state, back button, etc.)
The above class can be called if a history flag was called, which could become responsible for assigning initial state data. Primarily, this is because the JSON data object that's being around in this JS method contains already a lot of the crucial route data, and param information for that route needed in the backend PHP, which comes from the annotations.
So the idea is if I add accessibility for a history state title and URL to the annotations, then I will have access to that information right there available to define the initial state, if flagged, right inside the an ajax.done(), inside this main JS routing method.
Now we can pass state back and forth two ways between the db and realtime client-side async. You can use an observer, or anything, from there front-end, and jobs/queues on the backend to keep it fully reactive. (use React too :-))
EDIT I'm not so sure that's what I was thinking, it looks like its making me set the values of the title and url for this inside the return statement of the PHP function, where I want it set in the annotation (see return 'Matthias Noback';)
So I'm trying this, but where do I set these titles at?
<?php
namespace Blah\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
/**
* #Annotation
*/
class HistoryAnnotationController
{
//history state params are out properties here..
/**
* #var
*/
private $url;
/**
* #var
*/
private $title;
/**
*
*/
public function __construct()
{
}
/**
* #return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* #return mixed
*/
public function getUrl()
{
return $this->url;
}
}
I want to set it WAY back here, so the ajax that calls this route has access to it.. (look for #historyApiTitle in this code, etc..)
<?php
namespace Blah\Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
Symfony\Component\HttpFoundation\JsonResponse,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Method,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Template,
Blah\Bundle\Entity\Test,
Doctrine\ORM\Query; //for hydration
class StuffController
{
/**
* #Route("/some/route/name/{test}", name="some_route_name", options={"expose"=true})
* #param $test
* #return mixed
* #historyApiTitle('This is the get something page')
* #historyApiUrl('/get_something')
*/
public function getSomethingAction($test)
{
$em = $this->getDoctrine()->getManager();
$dql = "
SELECT s
FROM BlahBundle:Stuff s
WHERE s.test = :test";
$query = $em->createQuery($dql);
$query->setParameter('test', $test);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($query,
$this->get('request')->query->get('page', 1), 1000);
return $this->render('BlahBundle:Stuff:get_something.html.twig', array('pagination' => $pagination));
}
}
Q So looking at these TWO code examples, how do I connect the dots between the two to get this to work?
Yes you can annotations classes you can follow the following tutorial Creating Custom annotations Classes
Basic rules are the follows:
Your class should have the #Annotation -phpdoc comment
/**
* #Annotation
*/
class CustomAnnotation
{
public function __construct($options) {}
}
In Your Needed class just use it in standard way;
class Person
{
/**
* #CustomAnnotation("option")
*/
public function getName()
{
return 'some stuff';
}
}
You should looks at the AOPBundle, it allows you to do treatement from your personnals annotations. But I don't thinks trying to do annotations in the view is a good idea. You need to parse the javascript with php, and it sounds bad.