zf create project path name-of-profile file-of-profile - php

I was not able to find a good resource which is describing the following Zend_Tool command:
zf create project path name-of-profile file-of-profile
Not even here:
http://framework.zend.com/manual/en/zend.tool.usage.cli.html
Does somebody know a good resource regarding this command?
Note: I'm interested in the name-of-profile and file-of-profile part. Usage, examples, etc.
Maybe even a visual approach like in this references:
http://marklodato.github.com/visual-git-guide/index-en.html
http://osteele.com/archives/2008/05/commit-policies

I am not familiar enough with the internals of ZF Tool Project, but have a look at
http://framework.zend.com/manual/en/zend.tool.project.create-a-project.html
http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Tool/Project/Provider/Project.php
Afaik (which is not much) Zend Tool maintains an XML file to keep track of your project. This is required for any subsequent actions to be applied correctly to your project through Zend Tool.
The DocBlock for the create action in the Project Provider says:
/**
* create()
*
* #param string $path
* #param string $nameOfProfile shortName=n
* #param string $fileOfProfile shortName=f
*/
When run without the two optional arguments, the method will eventually create a new project file with
$newProfile = new Zend_Tool_Project_Profile(array(
'projectDirectory' => $path,
'profileData' => $profileData
));
with $profileDate being the content of the default configuration file. If you specify $fileOfProfile, you can override the configuration file and supply your own file, e.g.
if ($fileOfProfile != null && file_exists($fileOfProfile)) {
$profileData = file_get_contents($fileOfProfile);
}
Obviously, you have to supply a full path to the file for this to work. The alternative is to supply a file identifier, which Zend Tool will then try to find in a predefined location, e.g.
$storage = $this->_registry->getStorage();
if ($profileData == '' && $nameOfProfile != null && $storage->isEnabled()) {
$profileData = $storage->get('project/profiles/' . $nameOfProfile . '.xml');
}
I have no clue what the storage part is about. Like I said, I am not familiar with Zend Tool's inner workings. If I understand correctly, you can use the additional two arguments to load an existing project in a new location or customize the default one.
You might want to browse the ChangeLog to find out more about it.

Related

openapi-generator-cli not generating documentation from PHP file

Background: I have installed composer installed zircote/swagger-php and have installed openapi-generator-cli with apt-get.
I am not sure whether or not I am attempting to use these tools correctly, however I've been unable to find documentation pointing me in any direction.
I have a controller file with a whole bunch of code in it. I want to test whether or not I can generate a json file from it using open api annotation.
Here's a sample of my code (I've cut out unrelated chunks of it):
<?php
/**
* #OA\Info(title="My First API", version="0.1")
*/
class Apiv1_LocationController extends App_Controller_API
{
/* Publicly exposed attributes and the field type for filtering */
protected $_exported = array('id','created','modified','name','address','phone','external_id','postcode','country','timezone','date_format','lacps','staff_count');
protected $_schematypes = array(
'string' => ['name','address','phone','external_id','postcode','country','timezone','date_format'],
'int' => ['id','staff_count'],
'timestamp' => ['created','modified'],
'complex'=> ['lacps'],
);
{more unrelated code...}
/**
* #OA\Get(
* path="/api/resource.json",
* #OA\Response(response="200", description="An example resource")
* )
*/
public function getAction()
{
{code inside action...}
}
}
The cli command I use:
openapi-generator-cli generate -g php -i <path_to_LocationController>
I get the following error:
[main] INFO o.o.c.ignore.CodegenIgnoreProcessor - No .openapi-generator-ignore file found.
Exception in thread "main" java.lang.RuntimeException: Issues with the OpenAPI input. Possible causes: invalid/missing spec, malformed JSON/YAML files, etc.
This leads me to believe I am using the openapi-generator-cli tool incorrectly, since I wouldn't be expecting to need a JSON or YAML file, I am trying to generate that file.
I'll keep trying, but if someone could help me realized what I'm doing wrong or how I'm misunderstanding the tool, I'd really appreciate it.
So I realized I'd been going about this in entirely the wrong way.
I used the zircote/swagger-php library to generate the JSON file I required with the following command (In the directory where I wanted the JSON to be generated):
./<path_to_vendor_directory>/vendor/zircote/swagger-php/bin/openapi --pattern "*Controller.php" --output <name_of_file>.json --format json <location_to_search_from_recursively>

BasePath attribute always empty in request object, working on PHPUnit tests

I have a controller has an action that looks something like this:
/**
* #Route("/my_route_path", name="my_route_name")
*/
public function doSomethingAction(Request $request)
{
$myPath = $request->getScheme().'://'.$request->getHttpHost().''.$request->getBasePath();
$data = file_get_contents($myPath. '/data_folder/data.json');
return $this->render('#Entry/my_template.html.twig', array(
'data' => json_decode($data, true)
));
}
And I create a functional test for this controller like this:
/** #test */
public function doSomething_should_success()
{
$client = static::createClient();
$crawler = $client->request('GET', '/my_route_path');
$this->assertEquals(200, $client->getResponse()->getStatusCode());
}
But I can't run the functional test I still get : Failed asserting that 500 is identical to 200
So, after I checked the test.log file I find this error : file_get_contents(http://localhost/data_folder/data.json) : failed to open stream
As now the problem is comming from $request->getBasePath() because always contain empty string but the expected behaviour is return PATH_TO_MY_PROJECT_FOLDER\web in my case must return projects\web_apps\MY_PROJECT_FOLDER_NAME\web
So, the simplified question: why the request object always contain an empty basePath string in the unit test but it works very well on the browser.
The Request object helps you handle the request of a client, that is something like GET /my_route_path plus lots of headers and a server that is directed at.
The web server passes those information on to php and symfony, and symfony will turn this into a Request object. Symfony has usually one entry point, which is public/index.php (symfony 4) or web/app.php (symfony 3) which is assumed to be / or possibly /basePath/ (the basepath will be communicated by the web server and handled by Symfony).
Symfony will generate a Request object, where the basepath is essentially abstracted away, and whenever you generate a url (via Controller::generateUrl) the base path is taken into account. that's why the basepath is important for Requests.
This is actually described pretty well in the comments of the Request's functions:
getBasePath vs getPathInfo.
However, this only concerns the public facing URLs and doesn't have anything to do with how you structure your project and where that project is located, because that's completely irrelevant to the Request (separation of concerns and stuff).
So I guess, you are actually looking for the root directory of your project.
To find the location of your project dir, there is the very base version, where you directly use the PHP magic var __DIR__ which contains the directory the current script file is in, and you can navigate from there. since controllers are usually located such that their path is projectdir/src/Controller/TheController.php a __DIR__.'/../.. would give you the projectdir. However, that's not really clean. The better version:
Depending on the symfony version you're using, you should retrieve the project dir via the ParameterBagInterface (symfony 4)
function doSomethingAction(ParameterBagInterface $params) {
$projectDir = $params->get('kernel.project_dir');
}
or via the container (symfony 3) see also: new in symfony 3.3: A simpler way to get the project root directory
function doSomethingAction() {
$projectDir = $this->getParameter('kernel.project_dir');
}
In my case I had to inyect RequestStack $stackand access the main request, after that my "BasePath" has value. This is because I where in a subrequest and I had to access to the top level of the request.
This post helped me to understood: Symfony2 - get main request's current route in twig partial/subrequest
/**
* #Route("/myroute", name="myroute")
*/
public function myroute(RequestStack $stack)
{
$request = $stack->getMainRequest();
$route = $request->getPathInfo();
}

Yii2: How to force using fallback MessageFormatter method?

My website is with a hosting provider that has the MessageFormatter class available on the server (Linux, PHP 7.0.27) but it is an old ICU version (4.2.1) that doesn't support my message {number,plural,=0{# available} =1{# available} other{# available}} and gives the error:
Message pattern is invalid: Constructor failed
msgfmt_create: message formatter creation failed: U_ILLEGAL_CHARACTER
...because of the =1 and =2 notation.
I'm not able to make changes to the server so how can I force using the fallback method provided by Yii2 which works just fine?
There is this hacky way you can try.
Copy the yii\i18n\MessageFormatter code to a new file. Name it MessageFormatter.php and place somewhere in your application (but not in vendor folder).
In this new file change the format() method to:
public function format($pattern, $params, $language)
{
$this->_errorCode = 0;
$this->_errorMessage = '';
if ($params === []) {
return $pattern;
}
return $this->fallbackFormat($pattern, $params, $language);
}
Don't change anything else (including namespace).
Now let's use Yii mapping.
Find a place in your application when you can put code that will be run every time in bootstrapping phase. Good place for this is common/config/bootstrap.php if you are using "Advanced Template"-like project.
Add there this line:
Yii::$classMap['yii\i18n\MessageFormatter'] = 'path/to/your/MessageFormatter.php';
Obviously change the path to the one you've chosen. Now Yii autoloader will load this class from your file instead of the original Yii vendor folder (as mentioned in Class Autoloading section of the Guide).
In the modified file MessageFormatter method presence of intl library is never checked so fallback is used as default.
The downside of this trick is that you need to update manually your file every time original Yii file is changed (so almost every time you upgrade Yii version).
Another approach is to configure I18N component in your application to use your custom MessageFormatter where you can extend the original file and just override format() method inside without modifying class map.

Moodle File API get folder for SCORM module by moduleid

I'm developing a Moodle web service plugin.
I need to get the folder where a SCORM lesson has been unzipped having module_id as input parameter.
something like:
function get_root_folder_for_scorm_module($module_id){
global $USER;
$context = get_context_instance(CONTEXT_USER, $USER->id);
self::validate_context($context);
$fs = get_file_storage();
$manifest = $fs->get_file($context->id, 'mod_scorm', 'content', $module_id, '/', 'imsmanifest.xml');
return $manifest->get_filepath(); // Exception here. $manifest is null
}
This won't work because $manifest is null
Where $module_id is returned by standard moodle webservice method core_course_get_contents
There are many different ways a scorm module can work. As far as I know the content is not always served locally, and not always coming from a zip file.
If you know that your package is going to be available locally you're on the right track, though the parameters passed to get_file seem wrong.
Without looking at the source, I can tell that the context used is incorrect. Most likely the context in which the files are stored will be the module context. Also, looking briefly at the functions scorm_pluginfile and scorm_get_file_info in mod/scorm/lib.php it seems that the itemid (where you are using $module_id is always 0.
I suggest that you also have a look at scorm_parse in mod/scorm/locallib.php where we can find this:
$packagefile->extract_to_storage($packer, $context->id, 'mod_scorm', 'content', 0, '/');

Symfony 2 - how to parse %parameter% in my own Yaml file loader?

I have a Yaml loader that loads additional config items for a "profile" (where one application can use different profiles, e.g. for different local editions of the same site).
My loader is very simple:
# YamlProfileLoader.php
use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Yaml\Yaml;
class YamlProfileLoader extends FileLoader
{
public function load($resource, $type = null)
{
$configValues = Yaml::parse($resource);
return $configValues;
}
public function supports($resource, $type = null)
{
return is_string($resource) && 'yml' === pathinfo(
$resource,
PATHINFO_EXTENSION
);
}
}
The loader is used more or less like this (simplified a bit, because there is caching too):
$loaderResolver = new LoaderResolver(array(new YamlProfileLoader($locator)));
$delegatingLoader = new DelegatingLoader($loaderResolver);
foreach ($yamlProfileFiles as $yamlProfileFile) {
$profileName = basename($yamlProfileFile, '.yml');
$profiles[$profileName] = $delegatingLoader->load($yamlProfileFile);
}
So is the Yaml file it's parsing:
# profiles/germany.yml
locale: de_DE
hostname: %profiles.germany.host_name%
At the moment, the resulting array contains literally '%profiles.germany.host_name%' for the 'hostname' array key.
So, how can I parse the % parameters to get the actual parameter values?
I've been trawling through the Symfony 2 code and docs (and this SO question and can't find where this is done within the framework itself. I could probably write my own parameter parser - get the parameters from the kernel, search for the %foo% strings and look-up/replace... but if there's a component ready to be used, I prefer to use this.
To give a bit more background, why I can't just include it into the main config.yml: I want to be able to load app/config/profiles/*.yml, where * is the profile name, and I am using my own Loader to accomplish this. If there's a way to wildcard import config files, then that might also work for me.
Note: currently using 2.4 but just about ready to upgrade to 2.5 if that helps.
I've been trawling through the Symfony 2 code and docs (and this SO question and can't find where this is done within the framework itself.
Symfony's dependency injection component uses a compiler pass to resolve parameter references during the optimisation phase.
The Compiler gets the registered compiler passes from its PassConfig instance. This class configures a few compiler passes by default, which includes the ResolveParameterPlaceHoldersPass.
During container compilation, the ResolveParameterPlaceHoldersPass uses the Container's ParameterBag to resolve strings containing %parameters%. The compiler pass then sets that resolved value back into the container.
So, how can I parse the % parameters to get the actual parameter values?
You'd need access to the container in your ProfileLoader (or wherever you see fit). Using the container, you can recursively iterate over your parsed yaml config and pass values to the container's parameter bag to be resolved via the resolveValue() method.
Seems to me like perhaps a cleaner approach would be for you to implement this in your bundle configuration. That way your config will be validated against a defined structure, which can catch configuration errors early. See the docs on bundle configuration for more information (that link is for v2.7, but hopefully will apply to your version also).
I realise this is an old question, but I have spent quite a while figuring this out for my own projects, so I'm posting the answer here for future reference.
I tried a lot of options to resolve %parameter% to parameters.yml but no luck at all. All I can think of is parsing %parameter% and fetch it from container, no innovation yet.
On the other hand I don't have enough information about your environment to see the big picture but I just come up with another idea. It can be quite handy if you declare your profiles in your parameters.yml file and load it as an array in your controller or service via container.
app/config/parameters.yml
parameters:
profiles:
germany:
locale: de_DE
host_name: http://de.example.com
uk:
locale: en_EN
host_name: http://uk.example.com
turkey:
locale: tr_TR
host_name: http://tr.example.com
You can have all your profiles as an array in your controller.
<?php
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
$profiles = $this->container->getParameter('profiles');
var_dump($profiles);
return $this->render('AcmeDemoBundle:Default:index.html.twig');
}
}
With this approach
you don't have to code a custom YamlLoader
you don't have to worry about importing parameters into other yml files
you can have your profiles as an array anytime you have the $container in your hand
you don't have to load/cache profile files one by one
you don't have to find a wildcard file loading solution
If I got your question correctly, this approach can help you.

Categories