Symfony- Calling validation classl using variables - symfony

I am trying to do validation in symfony by using variables as shown below
$call= 'Assert\\'.$k2;
//echo $k2.'-'.$item;
echo $call;
//exit;
$arrayConstraint = new $call($item);
//$arrayConstraint = new Assert\NotBlank(null);
$errors = $this->get('validator')->validate(
$arr_item,
$arrayConstraint
);
This code gives error:
Attempted to load class "NotBlank" from namespace "Assert".
Did you forget a "use" statement for "Symfony\Component\Validator\Constraints\NotBlank"?
Whereas I am using the proper namespace(im including the class on top).
Whenevr i uncomment this line
$arrayConstraint = new Assert\NotBlank(null);
and comment this
//$arrayConstraint = new $call($item);
it works perfectly fine.
I guess this has something to do with calling classes using variables. Any ideas for a workaround?
Any help will be deeply appreciated

Finally I did it, by adding the whole path(namespace) to the variable.
$call= "Symfony\\Component\\Validator\\Constraints\\".$k2;
This is working now.

Related

Extbase: Command Controller is not getting Registered

I am new to Extbase. There are two xml files that I want to access. One is abc.dll?type=xml from which I select the ID and then use this Id to fetch the values of other XML file(xyzzy.dll?type=xml and save all the data to the db. I want to create a task in Extbase and run it from command line.
Below is my code:
ext_localconf.php
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers'][] = 'TYPO3\Example\Command\XMLFetcherCommandController';
XMLFetcherCommandController:
namespace TYPO3\Example\Command;
class XMLFetcherCommandController extends \TYPO3\CMS\Extbase\Mvc\Controller\CommandController{
/**
* xmlload
*
* #return void
*/
public function findCommand(){
$path="http://abc.dll?type=room&content=xml";
$readXML=file_get_contents($path);
$xml = simplexml_load_string($readXML, "SimpleXMLElement",LIBXML_NOCDATA); $objectManager=\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$classesRepository = $objectManager->get('TYPO3\\Example\\Domain\\Repository\\ClassesRepository');
$json=json_encode($xml);
$xmlArray=json_decode($json,true);
$serialized_array = serialize($xmlArray);
$unserialized_array = unserialize($serialized_array);
$rooms = $unserialized_array['Rooms']['Room'];
foreach($rooms as $room){
$fetchXML= \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\Example\\Domain\\Model\\Classes');
$fetchXML->setRoomKey($room['Key']);
$fetchXML->setRoomID($room['ID']);
$classesRepository->add($fetchXML);
$newpaths[]='http:/xyz.dll?content=xml&type=room&id='.$room['ID'];
foreach($newpaths as $newpath){
$readLessons=file_get_contents($newpath);
$xmlLessons= simplexml_load_string($readLessons, "SimpleXMLElement",LIBXML_NOCDATA);
$objectManager=\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$classesRepository = $objectManager->get('Example\\Example\\Domain\\Repository\\ClassesRepository');
$json=json_encode($xml);
$xmlArray=json_decode($json,true);
$serialized_array = serialize($xmlArray);
$unserialized_array = unserialize($serialized_array);
$Lessons = $unserialized_array['Lesson'];
foreach ($Lessons as $Lesson) {
$fetchXMLNew= \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Example\\Example\\Domain\\Model\\Classes');
$date=date('Ymd',strtotime($Lesson['Date']));
$start=date('Hi',strtotime($Lesson['Start']));
$finish=date('Hi',strtotime($Lesson['Finish']));
$startdatetime=date('YmdHi',strtotime("$date$start"));
$finishdatetime=date('YmdHi',strtotime("$date$finish"));
$fetchXMLNew->setStartdatetime($startdatetime);
$fetchXMLNew->setEnddatetime($finishdatetime);
$classesRepository->add($fetchXML);
}
}
}
$classesRepository->persistAll();
}
}
}
?>
When I run- php cli_dispatch.phpsh extbase help - from cmd, I could not see my command controller which means it is not registered properly. Could you suggest if this is the right way to do it? At First, I created a Service and tried to call it, but since there was a lot of data it was taking a lot of time.
Maybe it does not work, becouse your class can not be loaded with autoloader?
If a class is not available, it will not be registerd.
(#see CommandManager->getAvailableCommands !class_exists($className)).
I think you need to escape the back slashes (=> Double Slashes)
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers'][]
= 'TYPO3\\Example\\Command\\XMLFetcherCommandController';
If this not work, you can also check the Namespace of your class. Why does it start with "TYPO3"?
If this also not work, you can try load your class hardcoded with require_once in AdditionalConfiguration.php to figure out whats wrong

Why is my localized variable keep saying undefined?

I am little new to wordpress. I have tried so many different attempts trying to make this work but can seem to resolve the issue.
It keeps saying that ML_MOVIE_LISTING is undefined, when i try to localize it.
Below is my php code and javascript file.
Any help would really appreciated. Thanks!
function admin_scripts (){
wp_enqueue_style("admin-style",plugins_url("style-admin.css",__FILE__));
wp_enqueue_style("jquery-ui","https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/external/jquery/jquery.js");
wp_enqueue_script("main_js",plugins_url("main.js",__FILE__),["jquery","jquery-ui-sortable"]);
wp_localize_script("ml-script","ML_MOVIE_LISTING",[
"token"=>wp_create_nonce("ml-token")
]);
}
add_action("admin_init","admin_scripts");
JS CODE
jQuery(document).ready(function($){
var movie_sort_list = $(".movie-sort-list"),
order_save_msg = $(".order-save-msg"),
order_save_error = $(".order-save-err");
console.log(ML_MOVIE_LISTING);
}
I just found out the reason why it wasn't working was because the name in the first parameter was different then the name of the first paramaeter in
wp_enqueue_script() They both have to be the same as shown below
wp_enqueue_script("main_js",plugins_url("main.js",__FILE__),["jquery","jquery-ui-sortable"]);
wp_localize_script("main_js","ML_MOVIE_LISTING",[
"token"=>wp_create_nonce("ml-token")
]);

PHPexcel load an html formatted variable

i am trying to load an html snippet variable into a spreadsheet.I have differnet sections which may have different dynamic html content. So i cant just convert manually.
$dynamic_code_snippet = '<ul><li>item one</li><li>item two</li></ul>';
At the moment i am trying this but get errors:
if(!empty($dynamic_code_snippet)){
$excelHTMLReader = PHPExcel_IOFactory::createReader('HTML');
$snippet = $excelHTMLReader->load($dynamic_code_snippet);
$snippetWriter = PHPExcel_IOFactory::createWriter($snippet,'Excel2007');
ob_start();
$snippetWriter->save('php://output');
$code = ob_get_clean();
$table->getActiveSheet()->setCellValue('A1, $code);
}
I get an error:
Fatal error: Uncaught PHPExcel_Reader_Exception: Could not open in PHPExcel\Reader\Abstract.php on line 196
Do you think its because its a snippet not a full page html document(no <html><head><body> tags)?
Can it be done? or do i have to rethink?
PHPExcel does provide a helper wizard that can be used to convert basic html markup to Riche Text Objects that can be set as a cell value:
$wizard = new PHPExcel_Helper_HTML;
$richText = $wizard->toRichTextObject($html);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', $richText);
However, only some markup tags are actively supported, and ordered/unordered lists aren't included.
If you want to take a look at it, and see how the code actually works, possibly modify it to work with lists, then it's the HTML.php file in /Classes/PHPExcel/Helper.

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.

Resources