php - phantomjs alerts - php

I am not very familiar with javascript and not sure how to handle alerts in php script when using phantomjs.
This is my code:
$this->clickcontrol(Constants::LINK, 'delete', false);
$this->acceptAlert();
So how should I change this to handle alerts in phantomjs

This looks like PHPUnit's PHPUnit_Extensions_Selenium2TestCase.
When faced with this, I have created following function (I put it into a common base test case class myself, but it also can be in your test class):
protected function waitForAlert($expectedText, $timeout = 10000)
{
$this->waitUntil(
function () use ($expectedText) {
if ($this->alertText() == $expectedText) {
return true;
}
},
$timeout
);
$this->acceptAlert();
}
Then in the test itself you can use it as such:
$this->waitForAlert('You need a complete profile');
If there is no alert it will fail after the timeout set
Hope this helps ;)

Related

Bolt CMS Events

I am working with the save event but having limited luck.
I have currently tried two ways but to limited success.
1) I can either never get the function to fire,
2) I am not too sure what to pass into the function for method two.
All I am trying to do is to dump the event information out on content save.Any help greatly appreciated, really loving this CMS
Attempt One -- never runs the function at all
class Extension extends BaseExtension
{
public function initialize() {
$this->addCss('assets/extension.css');
$this->addJavascript('assets/start.js', true);
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE, 'postSave');
}
function postSave(\Bolt\StorageEvent $event)
{
dump($event);
}
Attempt two -- what do I input as a parameter?
class Extension extends BaseExtension
{
public function initialize() {
$this->addCss('assets/extension.css');
$this->addJavascript('assets/start.js', true);
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE,$this->postsave($this->?????));
}
function postSave(\Bolt\StorageEvent $event)
{
dump($event);
}
Hopefully my answer doesn't come too late!
You simply can modify the content and save it back to the database:
public function postSave(\Bolt\Events\StorageEvent $event) {
// get the content
$content = $event->getContent();
// get a field out of the contenttype
$data = $content->get("myField");
// now modify $data here
$data = "new data - what ever you want";
// set data to the content
$content->setValue("data", $data);
// write the modified content to the database
$this->app['storage']->saveContent($content);
}
Note that the function gets fired every time you save contents. So just add an if-statement like this to just modify content you really want to:
if ($event->getContentType() == "my_type")
The parameter needed is a php callback the format for this is something like this:
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE, array($this, 'postSave'));
That syntax is saying to run the postSave method within the current class. So this would work with your example number 1.
Now you can dump the event in your postSave method and see the results.

Ajax polling with Symfony Process component

I am starting a long running task that returns incremental output about the tasks progress with the Symfony Process component.
One of the examples shows how to get real time output and another example shows how to run an asynchronous task.
What I am trying to achieve is sto pass the result of getIncrementalOutput back to the ajax polling function so I can update the front end in real time.
It seems in either case the process->start() is blocking because my ajax call takes a minute to return and by that time the task has finished.
I guess I'm trying to avoid writing the progress to a db or a file and get the output directly from the running PHP task.
Not sure it's possible.
Although I don't fully understand what you want to create, I have written something similar and looking at it might answer your question:
First I created a Command that does the long-running task:
class GenerateCardBarcodesCommand extends Command
{
protected function configure()
{
$this
->setName('app:generate-card-barcodes')
->setDescription('Generate the customer cards with barcodes')
->addArgument('id', InputArgument::REQUIRED, 'id of the Loy/Card entity')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument('id');
// generate stuff and put them in the database
}
}
In the controller the Process is started and there's an ajax action
class CardController extends Controller
{
public function newAction(Request $request)
{
// run command in background to start generating barcodes
// NOTE: unset DYLD_LIBRARY_PATH is a fix for MacOSX develop using MAMP.
// #see http://stackoverflow.com/questions/19008960/phantomjs-on-mac-os-x-works-from-the-command-line-not-via-exec
$process = new Process(sprintf('unset DYLD_LIBRARY_PATH ; php ../../apps/spin/console spin:loy:generate-card-barcodes %d', $entity->getId()));
$process->start();
sleep(1); // wait for process to start
// check for errors and output them through flashbag
if (!$process->isRunning())
if (!$process->isSuccessful())
$this->get('session')->getFlashBag()->add('error', "Oops! The process fininished with an error:".$process->getErrorOutput());
// otherwise assume the process is still running. It's progress will be displayed on the card index
return $this->redirect($this->generateUrl('loy_card'));
}
public function ajaxCreateBarcodesAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $this->getEntity($id);
$count = (int)$em->getRepository('ExtendasSpinBundle:Loy\CustomerCard')->getCount($entity);
return new Response(floor($count / ($entity->getNoCards() / 100)));
}
}
// in the twig template the ajax is retrieved, which is simply a number from 0 to 100, which is used in the jquery ui progressbar.
{{ 'Processing'|trans }}...
<script type="text/javascript">
$(function() {
function pollLatestResponse() {
$.get("{{ path('loy_card_ajax_generate_barcodes', {'id': entity[0].id}) }}").done(function (perc) {
if (perc == 100)
{
clearInterval(pollTimer);
$('#download-{{entity[0].id}}').show();
$('#progress-{{entity[0].id}}').hide();
}
else
{
$('#progress-{{entity[0].id}}').progressbar("value", parseInt(perc));
}
});
}
var pollTimer;
$(document).ready(function () {
$('#progress-{{entity[0].id}}').progressbar({"value": false});
pollTimer = setInterval(pollLatestResponse, 2000);
});
});
</script>

Return synchronously when a React/Promise is resolved

I need to return from a function call once a React/Promise has been resolved. The basic idea is to fake a synchronous call from an ansynchronous one. This means that the outer function must return a value once a promise has been resolved or rejected.
This is to create a driver for RedBeanPHP using React/Mysql. I am aware that this will likely lead to CPU starvation in the React event loop.
My initial idea was to use a generator then call yield inside a \React\Promise\Deferred::then callback.
function synchronous()
{
$result = asynchronous();
}
function asynchronous()
{
$deferred = new \React\Promise\Deferred;
$sleep = function() use ($deferred)
{
sleep(5);
$deferred->resolve(true);
};
$deferred->then(function($ret) {
yield $ret;
});
$sleep();
}
The PHP generator class, AFAICT, is only directly constructable by the PHP engine itself. The then callback would need to directly invoke send on the generator of the asynchronous function for this to work.
PHP lacks both continuations as well as generator delegation, which would make it possible to call yield from inside a nested callback, making this entirely impossible to achieve for the moment.
ReactPhp offers the async tools package which has an await function.
Code can then become:
function synchronous()
{
$result = \React\Async\await(asynchronous());
}
function asynchronous()
{
$deferred = new \React\Promise\Deferred;
$sleep = function() use ($deferred)
{
sleep(5);
$deferred->resolve(true);
};
$sleep();
return $deferred->promise();
}

Check whether FirePHP is installed in PHP code

Is there any way to determine whether FirePHP is installed on the server (via PEAR)? I'd like to make possible logging in FirePHP but also not to crash the code for everyone without that tool.
The example, how I imagine it should work:
$message = "hello";
function log($message) {
if (library_exists('FirePHPCore/fb.php')) {
require_once('FirePHPCore/fb.php');
ob_start();
\FB::log($message);
} else {
SomeBoringLogger::log($message);
}
}
I haven't found anything like my library_exists method. Is there anything like that in PHP?
#include_once('FirePHPCore/fb.php'); // Ignore any errors here, as we check for existance
if (class_exists('FirePHP')) { // Do something after this
http://php.net/manual/en/function.class-exists.php
FirePHP uses FirePHP as its class name, so if it is available, that class should be defined
For PHP 5.3.2 or later, use zerkms's suggestion:
(!stream_resolve_include_path('FirePHPCore/fb.php')===FALSE)
Use include_once, so it doesn't kill the request. As #Brad suggests, use class_exists afterwards.
$message = "hello";
safe_include_once('FirePHPCore/fb.php');
if (class_exists('FB')) {
function log($message) {
//using FirePHP
}
} else {
function log($message) {
SomeBoringLogger::log($message);
}
}
function safe_include_once($path) {
if ($path = stream_resolve_include_path($path)) {
include_once($path);
}
}
[Edit] Using stream_resolve_include_path in safe_include_path.
[Edit2] Faster runtime logging.
file_exists() can be used for your case.

Instantiating a AMF PHP class not working

I am trying to use AMF PHP to pass variables to a flash file, thus far I cannot see anything wrong with my code, but I have very little experience with creating classes, so here it goes, here is my code,
index.php:
<?php
include "amfphp/services/flashMe.php";
$session = true;
if ($session == true) {
$uid = '12345';
$thing = new flashMe;
$thing->push($uid);
} else {
//login
}
?>
flashMe.php:
<?php
class flashMe {
public function __construct() {
}
public function push($one)
{
return $one;//sends the uid to the flash file?
}
}
?>
Flash is looking for the flashMe class and the push method within that class, but I keep getting null variables in my flash file when I run it, is there something wrong with this code?
Thanx in advance!
Your index.php file is unnecessary.
Your second file is incomplete. Here is the example from the docs for their "hello world" class file:
<?php
class HelloWorld
{
function HelloWorld()
{
$this->methodTable = array
(
"say" => array
(
"access" => "remote",
"description" => "Pings back a message"
)
);
}
function say($sMessage)
{
return 'You said: ' . $sMessage;
}
}
?>
This file should be saved as "HelloWorld" matching the "class HelloWorld" you have named in the php file (you did this part right with FlashMe).
The example file in the docs for the Flash piece (in actionscript) is here:
import mx.remoting.*;
import mx.rpc.*;
import mx.remoting.debug.NetDebug;
var gatewayUrl:String = "http://localhost/flashservices/gateway.php"
NetDebug.initialize();
var _service:Service = new Service(gatewayUrl, null, 'HelloWorld', null , null);
var pc:PendingCall = _service.say("Hello world!");
pc.responder = new RelayResponder(this, "handleResult", "handleError");
function handleResult(re:ResultEvent)
{
trace('The result is: ' + re.result);
}
function handleError(fe:FaultEvent)
{
trace('There has been an error');
}
The gateway URL should go to wherever your services can be reached. I'm sure if you try a few you'll find the right one. The neat thing about amfphp is that it allows you to also test your services out before you try implementing them in the gateway (if you go to the URL in your browser).
I'm pretty new to AMFPHP as well, but I've found the docs to be extraordinarily useful. If you need more help on classes, you can find more info on the PHP docs page.
You missed the parenthesis after new flashMe
$thing = new flashMe();
$thing->push($uid);
Amfphp or Zend AMF only allow you to call public methods on a remote class that is exposed by your gateway. You example is not a class and therefore no remote method can be called. This looks more like something that you would do with an http post.
http://framework.zend.com/manual/en/zend.amf.server.html

Categories