Call application->run() again - symfony

We have a symfony 2 console command app. Inside a command (extending \Symfony\Component\Console\Command\Command) we call another command.
Code:
$this->getApplication()->run(new StringInput('cache:flush'), new NullOutput());
This was working fine until the update to the recent Symfony version
But now I hit the exception in the following Symfony function (\Symfony\Component\Console\Input\ArgvInput::parseArgument())
private function parseArgument($token)
{
$c = count($this->arguments); ## $c is 0 !
// if input is expecting another argument, add it
if ($this->definition->hasArgument($c)) {
$arg = $this->definition->getArgument($c);
$this->arguments[$arg->getName()] = $arg->isArray()? array($token) : $token;
// if last argument isArray(), append token to last argument
} elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
$arg = $this->definition->getArgument($c - 1);
$this->arguments[$arg->getName()][] = $token;
// unexpected argument
} else {
throw new \RuntimeException('Too many arguments.'); ### this exception is thrown
}
}
Both of the commands (the original one dev:setup:run and the one we call cache:flush) do not need parameters.
References: https://github.com/netz98/n98-magerun/issues/90

This commit causes Symfony2 to not behave like expected, as you can see in the comments.
However, this change is reverted, but only in the Symfony2.2 branch (which is a mistake, I guess). You need to update your Console dependency to some 2.2.x version.
You can savely update to the 2.2.x version, because there are no BC breaks in the Console component (just some really cool features)

Related

Gosu system table query failing in Gunits

I have a Guidewire Gunit for a transformer in gosu which queries the system table to get a description for a result code which is working fine when run on the server but Gunit fails for the same.
I have tried the annotation #ServerTest for Gunit but that is failing as well.
The same code works fine in Gosu scratchpad.
PFA the code snippet as follows:
var resultCodes = Query.make(SystemTable).select().where(\elt -> elt.ResultCode == "AS01")
var description = ""
if(resultCodes != null && !resultCodes.isEmpty())
{
description = resultCodes.get(0).getFullDescription()
}
I'm getting the exception as follows :
java.lang.IllegalStateException: TableMetadataFactory cannot be used before it is started
Thanks,
Deepti
(Suggestion : )If your requirement is just to query based on some values.
Better dont use that .where() condition.
This is like SELECT * FROM <TABLE> and after getting all the data you are picking out your required result.
The best and the actual way is to use like
Query.make(TABLE_NAME).compare(TABLE_NAME#FIELD_NAME,Relop.Equals,"value_to_compare").select();
Query will be like
SELECT * FROM <TABLE_NAME> WHERE FIELD_NAME = FIELD_VALUE_TO_COMPARE;
While running Gunits, GW uses Shadow tables which will be basically empty.
Here if you are using OOTB entities, You can use Builder classes
or if you need to use some custom entities, use bundles to insert data first.
After inserting data into SystemTable (either using builder classes or bundles) run the below code.
var resultCodes = Query.make(SystemTable).compare(SystemTable#ResultCode ,Relop.Equals,"AS01").select()
foreach(result in resultCodes){
description = result.FullDescription
print("Output : "+description);
}
This happens when your RunLevel is set too low. Run levels below "NO_DAEMONS" will not load system tables. The default should be "NO_DAEMONS" so if you have an annotation on your test like this:
#RunLevel(gw.api.system.server.Runlevel.NONE)
either remove it or increase the level.
You can refactor your code like this:
uses gw.testharness.RunLevel
uses gw.api.database.Query
uses org.mockito.Mockito
uses gw.api.database.IQueryBeanResult
#RunLevel(NONE)
class StackOverflowTest {
function testDoQuery() {
var rs = Mockito.mock(IQueryBeanResult<SystemTable>)
var query = Mockito.mock(Query<SystemTable>)
Mockito.when(query.select()).thenReturn(rs)
var stackOverflow = Mockito.spy(new StackOverflow())
Mockito.doReturn(query).when(stackOverflow).getSystemTableQuery()
stackOverflow.doQuery()
Mockito.verify(stackOverflow, Mockito.times(1)).getSystemTableQuery()
Mockito.verify(query, Mockito.times(1)).select()
Mockito.verify(rs, Mockito.times(1)).iterator()
}
class StackOverflow {
function doQuery() {
var resultCodes = getSystemTableQuery().select().where(\elt -> elt.ResultCode == "AS01")
}
protected function getSystemTableQuery(): Query<SystemTable> {
return Query.make(SystemTable)
}
}
}

How can I remove a message shown from a different module?

In Drupal 7, I could use the following code.
if ($_SESSION['messages']['status'][0] == t('Registration successful. You are now logged in.')) {
unset($_SESSION['messages']['status']);
}
What is the equivalent code for Drupal 8?
First of all, in Drupal 8, messages are stored in the same $_SESSION['messages'] variable as before. However, using it directly is not a good way, as there exist drupal_set_message and drupal_get_messages functions, which you may freely use.
Then, status messages are shown using status-messages theme. This means that you can write preprocess function for it and make your alteration there:
function mymodule_preprocess_status_messages(&$variables) {
$status_messages = $variables['message_list']['status'];
// Search for your message in $status_messages array and remove it.
}
The main difference with Drupal 7, however, is that now status messages are not always strings, they may be objects of Markup class. They are wrappers around strings and may be cast to underlying string using magic method __toString. This means that they can be compared with and as strings:
function mymodule_preprocess_status_messages(&$variables) {
if(isset($variables['message_list']['status'])){
$status_messages = $variables['message_list']['status'];
foreach($status_messages as $delta => $message) {
if ($message instanceof \Drupal\Component\Render\MarkupInterface) {
if ((string) $message == (string) t("Searched text")) {
unset($status_messages[$delta]);
break;
}
}
}
}
}
Upon reading the related change record, I have discovered \Drupal::messenger()->deleteAll(). I hope this is useful to someone. UPDATE: You should NOT do this, as it removes all subsequent messages as well. Instead, do unset(['_symfony_flashes']['status'][0]).
You can install the module Disable Messages and filter out messages by pattern in the configuration of the module.
For this particular case, you can filter out the message using the following pattern in the module configuration
Registration successful.*
Although the question is asked around Drupal 8 which is no longer supported, the module works for Drupal 7, 8, 9.
You can solve your problem in more than one way.
First way:
You can make minor change in core user module.
Go on:
\core\modules\user\src\RegisterForm.php
In that file you have line you can change:
drupal_set_message($this->t('Registration successful. You are now logged in.'));
NOTE: This is easiest way but in this case way you will edit Drupal core module and that is generally bad practice. In further development you could have problems like overwrite your changes when you do update.
Second way:
You can disable end user message using module. Disable message module have option you need. In module configuration you have text box where you can filter out messages shown to the end users.
Third way:
Messages in Drupal 8 are stored in a session variable and displayed in the page template via the $messages theme variable. When you want to modify the variables that are passed to the template before it's invoked you should use preprocess function. In your case here you can just search string in session variable and alert/remove it before it's displayed.
function yourmodule_preprocess_status_messages(&$variables) {
$message = 'Registration successful. You are now logged in.';
if (isset($_SESSION['messages'])) {
foreach ($_SESSION['messages'] as $type => $messages) {
if ($type == 'status') {
$key = array_search($message, $messages);
if ($key !== FALSE) {
unset($_SESSION['messages'][$type][$key]);
}
}
}
}
}
(Note:Untested code, beware of typos)
Hope this helps!

How to clear all events in Google Calendar using API V3 PHP

I spent a long time to work out how to do the following using Google Calendar using API V3 in PHP
insert a new event
read all existing events
delete each existing event
However I would still like to know how to clear an entire Google Calendar to make my code faster, as the read & delete method is a little slow.
I've been trying to work out how to use the supplied Google function "clear" for this, and the documentation supplied by Google simply shows that I should be able to use the following command to achieve this:
$service->calendars->clear('primary');
Also within the Google Code there is a comment relating to the "calendars" collection of methods (where the clear function exists):
Typical usage is:
<code>
$calendarService = new Google_Service_Calendar(...);
$calendars = $calendarService->calendars;
</code>
So I've put this together with the preceding authentication code. I am sure the authentication is working OK as I've used that elsewhere, but the clear code is obviously wrong as I get error message:
Notice: Undefined variable: service in C:\wamp\www\googleapi\clear\index.php on line 39
I've tried using 'primary' as well as the main owner, and I've tried making the calendar private and public but to no avail.
Anyone who has got the clear method to work, please point me in the right direction.
This is the code I'm running so far:
<?php
session_start();
require_once '../google-api-php-client-master/autoload.php';
//Google credentials
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
$service_account_name = 'xxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client-master/API Project-xxxxxxx.p12';
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("Whatever the name of your app is");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
$_SESSION['service_token'] = $client->getAccessToken();
/* ------------------------- We are now properly authenticated ------------------- */
$calendarService = new Google_Service_Calendar($client);
$calendars = $calendarService->calendars;
$service->calendars->clear('primary');
?>
Just use your service calendar instance.
$service = new Google_Service_Calendar($client);
$calendar = $service->calendars->clear('primary');

Phpunit testing with ZF2 Album Module fails while connecting to AlbumTable

I am trying the phpunit in the Zf2 album module by following the online ZF2 tutorial. Below is the debug information.
Album\Model\AlbumTableTest::testFetchAllReturnsAllAlbums
Argument 1 passed to Album\Model\AlbumTable::__construct() must be an instance of Zend\Db\Adapter\Adapter, instance of Mock_TableGateway_fb3537df given, called in D:\www\zend2\tests\module\Album\src\Album\Model\AlbumTableTest.php on line 26 and defined
And the function used is
public function testFetchAllReturnsAllAlbums()
{
$resultSet = new ResultSet();
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway',
array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with()
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
$this->assertSame($resultSet, $albumTable->fetchAll());
}
And the 26th line mentioned in the debug information is
$albumTable = new AlbumTable($mockTableGateway);
Which calls to the following functon in Album\Model\AlbumTable::__construct()
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new Album());
$this->initialize();
}
Any help to over come this failed test is much appreciated.
Got it solved. I happened to see that the Album module given in the Zend Framework2 tutorial has been changed. I followed it once again to correct the changed codes. Now the mentioned issue has been sorted out.

Is it possible to find the function and/or line number that caused an error in ActionScript 3.0 without using debug mode?

I'm currently trying to implement an automated bug reporter for a Flex application, and would like to return error messages to a server along with the function/line number that caused the error. Essentially, I'm trying to get the getStackTrace() information without going into debug mode, because most users of the app aren't likely to have the debug version of flash player.
My current method is using the UncaughtErrorEvent handler to catch errors that occur within the app, but the error message only returns the type of error that has occurred, and not the location (which means it's useless). I have tried implementing getStackTrace() myself using a function name-grabber such as
private function getFunctionName (callee:Function, parent:Object):String {
for each ( var m:XML in describeType(parent)..method) {
if ( this[m.#name] == callee) return m.#name;
}
return "private function!";
}
but that will only work because of arguments.callee, and so won't go through multiple levels of function calls (it would never get above my error event listener).
So! Anyone have any ideas on how to get informative error messages through the global
error event handler?
EDIT: There seems to be some misunderstanding. I'm explicitly avoiding getStackTrace() because it returns 'null' when not in debug mode. Any solution that uses this function is what I'm specifically trying to avoid.
Just noticed the part about "I don't want to use debug." Well, that's not an option, as the non-debug version of Flash does not have any concept of a stack trace at all. Sucks, don't it?
Not relevant but still cool.
The rest is just for with the debug player.
This is part of my personal debug class (strangely enough, it is added to every single project I work on). It returns a String which represents the index in the stack passed -- class and method name. Once you have those, line number is trivial.
/**
* Returns the function name of whatever called this function (and whatever called that)...
*/
public static function getCaller( index:int = 0 ):String
{
try
{
throw new Error('pass');
}
catch (e:Error)
{
var arr:Array = String(e.getStackTrace()).split("\t");
var value:String = arr[3 + index];
// This pattern matches a standard function.
var re:RegExp = /^at (.*?)\/(.*?)\(\)/ ;
var owner:Array = re.exec(value);
try
{
var cref:Array = owner[1].split('::');
return cref[ 1 ] + "." + owner[2];
}
catch( e:Error )
{
try
{
re = /^at (.*?)\(\)/; // constructor.
owner = re.exec(value);
var tmp:Array = owner[1].split('::');
var cName:String = tmp.join('.');
return cName;
}
catch( error:Error )
{
}
}
}
return "No caller could be found.";
}
As a side note: this is not set up properly to handle an event model -- sometimes events present themselves as either not having callers or as some very weird alternate syntax.
You don't have to throw an error to get the stack trace.
var myError:Error = new Error();
var theStack:String = myError.getStackTrace();
good reference on the Error class
[EDIT]
Nope after reading my own reference getStackTrace() is only available in debug versions of the flash player.
So it looks like you are stuck with what you are doing now.

Resources