How to call a php function in psysh console? - php

Sorry, pretty noob to psysh.
Basically I have this function in my psysh/php:
>>> show $newcsr
class Tokyo {
private function sign($caCert,$userCsr) {
$caKey = file_get_contents('/home/nairobi/ca.key');
$userCert = openssl_csr_sign($userCsr, $caCert, $caKey, 365, ['digest_alg'=>'sha256']);
openssl_x509_export($userCert, $userCertOut);
return $userCertOut;
}
}
How do I call sign function to generate me a certificate in psysh console?

Psysh provides a sudo command for bypassing visibility restrictions, so you can do: sudo $newcsr->sign($caCert,$userCsr);

Related

Brocken metadata class generation via protobuf on alpine Docker images

Sometime ago I've used ubuntu image for PHP files generation via protoc lib and it generates some metadata classes with normal hashes used by protobuf.
It was generated smth like:
namespace MyApp\ProtobufMetadata\Schema\v1;
class Request
{
public static $is_initialized = false;
public static function initOnce() {
$pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
if (static::$is_initialized == true) {
return;
}
$pool->internalAddGeneratedFile(hex2bin(
"0acd010a236170692f636174616c6f672f736368656d612f76312f726571756573742e70726f746f121d6170692e636174616c6f672e736368656d612e76312e72657175657374221d0a0a47657452657175657374120f0a0776657273696f6e18012001280d4260ca022d4350515c5368617265645c53657276696365735c436174616c6f675c536368656d615c76315c52657175657374e2022d4350515c5368617265645c50726f746f6275664d657461646174615c436174616c6f675c536368656d615c7631620670726f746f33"
), true);
static::$is_initialized = true;
}
}
But now I need to use alpine usage.
I've created Dockerfile with installing protobuf from github:
ENV PROTOBUF_VERSION 3.19.4
ENV PROTOBUF_URL https://github.com/google/protobuf/releases/download/v"$PROTOBUF_VERSION"/protobuf-cpp-"$PROTOBUF_VERSION".zip
RUN curl -L -o protobuf.zip "$PROTOBUF_URL"
RUN unzip protobuf.zip && cd protobuf-"$PROTOBUF_VERSION" && ./configure && make -j$(nproc) && make install
RUN cd .. && rm protobuf.zip
But after this when I generates new classes it generates metadata classes in some strange view:
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: api/schema/v1/request.proto
namespace MyApp\ProtobufMetadata\Schema\v1;
class Request
{
public static $is_initialized = false;
public static function initOnce() {
$pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
if (static::$is_initialized == true) {
return;
}
$pool->internalAddGeneratedFile(
'
�
#api/schema/v1/request.protoapi.schema.v1.request"
GetRequest
version (
B`�-MyApp\\Services\\Catalog\\Schema\\v1\\Request�-MyApp\\ProtobufMetadata\\Catalog\\Schema\\v1bproto3'
, true);
static::$is_initialized = true;
}
}
Does anyone hit with similar problem?
Is any way to fix lib installation or some compile to return pretty code with hex2bin usage?
compilation was made via commands with RoadRunner usage:
[ -f ./protoc-gen-php-grpc ] || ./rr get-protoc-binary
&& chmod +x ./protoc-gen-php-grpc
&& ./rr compile-proto-files"
Host system is MacOS
This was done on purpose, your Alpine is probably just running a more recent version of protoc.
Here is the PR which removed the hex2bin call: https://github.com/protocolbuffers/protobuf/pull/8006

Implement locking for all commands in my Symfony app

I followed this guide: https://symfony.com/doc/current/console/lockable_trait.html and implemented the command lock feature for my one of my commands to see how it works. It worked as described and then I was going to implement it for all of my commands. But the issue is that I have about 50 commands and:
I do not want spent time adding the necessary code to each command
I want to have the centralized management of commands locking. I mean, adding extra option to regular commands so that they will be used by my future management center. For now I will need a pretty simple option protected function isLocked() for a regular command which will help me to manage if a command should have lockable feature.
So, I went to the source of \Symfony\Component\Console\Command\LockableTrait and after some time created the following listener to the event console.command:
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Lock\Lock;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\LockInterface;
use Symfony\Component\Lock\Store\FlockStore;
use Symfony\Component\Lock\Store\SemaphoreStore;
class LockCommandsListener
{
/**
* #var array<string, Lock>
*/
private $commandLocks = [];
private static function init()
{
if (!class_exists(SemaphoreStore::class)) {
throw new LogicException('To enable the locking feature you must install the symfony/lock component.');
}
}
public function onConsoleCommand(ConsoleCommandEvent $event)
{
static::init();
$name = $event->getCommand()->getName();
$this->ensureLockNotPlaced($name);
$lock = $this->createLock($name);
$this->commandLocks[$name] = $lock;
if (!$lock->acquire()) {
$this->disableCommand($event, $name);
}
}
private function disableCommand(ConsoleCommandEvent $event, string $name)
{
unset($this->commandLocks[$name]);
$event->getOutput()->writeln('The command ' . $name . ' is already running');
$event->disableCommand();
$event->getCommand()->setCode()
}
private function createLock(string $name): LockInterface
{
if (SemaphoreStore::isSupported()) {
$store = new SemaphoreStore();
} else {
$store = new FlockStore();
}
return (new LockFactory($store))->createLock($name);
}
private function ensureLockNotPlaced(string $name)
{
if (isset($this->commandLocks[$name])) {
throw new LogicException('A lock is already in place.');
}
}
}
I made some tests and it kind of worked. But I am not sure this is the right way of doing things.
Another problem is that I can not find the proper exit code when I disabled a command. Should I just disable it? But it seems that exit code would be a great feature here. Specially when it comes to this listener testing (PHPUnit testing).
And I also have with testing itself. How can I run commands in parallel in my test class. For now I have this:
class LockCommandTest extends CommandTest
{
public function testOneCommandCanBeRun()
{
$commandTester = new ApplicationTester($this->application);
$commandTester->run([
'command' => 'app:dummy-command'
]);
$output = $commandTester->getDisplay();
dd($output);
}
}
It will allow only to run my commands one by one. But I would like to run them both so after running the first one, the second will fail (with some exit code).
As for me the best way to make background task is doing it via supervisor, create config file, like:
[program:your_service]
command=/usr/local/bin/php /srv/www/bin/console <your:app:command>
priority=1
numprocs=1
# Each 5 min.
startsecs=300
autostart=true
autorestart=true
process_name=%(program_name)s_%(process_num)02d
user=root
this is the best way to be sure that your command will be ran only in one process

Return value from one Artisan command to another

I am attempting to call one Artisan (Laravel) command from another command. However, I need to be able to retrieve an array from the command that is called from the "main" command...
i.e
// Command 1
public function handle() {
$returnedValue = $this->call( 'test:command' );
dump( $returnedValue ); // <-- is 5
}
// Command 2
public function handle() {
return $this->returnValue();
}
private function returnValue() {
$val = 5;
return $val;
}
I have looked through the documentation and can't find a way to do this, so I was wondering if there was a way or if I need to re-think my approach.
Thanks!
Artisan Commands don't behave the same way as, for example, Controller functions. They return an exitCode, which in my testing was always 0 (couldn't get anything to return if an error is thrown).
Your approach won't work if you try to get a return value, but you can access \Artisan::output(); to see what exactly is sent by the first artisan command you call.
// FirstCommand.php
public function handle(){
\Artisan::call("second:command");
if(\Artisan::output() == 1){
$this->info("This Worked");
} else {
$this->error("This Didn't Work");
}
}
Note: I used \Artisan::call(); there's some apparent differences between the two where using $this->call() didn't work as expected, but \Artisan::call() did. $this->call() sent both 0 and 1 back, regardless of the actual code being executed; not sure what's up there. Tested on Laravel 5.0, which is quite behind the current, so maybe that's it.
// SecondCommand.php
public function handle(){
try {
$test = 1 / 1;
} catch (\Exception $ex){
$this->error("0");
}
$this->info("1");
}
Running php artisan first:command in my console returns:
$ php artisan first:command
This Worked
Now, if switch the code in $test to
$test = 1 / 0;
I get this in my console:
$ php artisan first:command
This Didn't Work
So, the rule here I guess is to avoid outputting anything in the second command prior to the result you want to check with \Artisan::output().

PHP shell_exec does not work for two different app version

I am experiencing an interesting strange issue with shell_exec...
Description
I develop PHP web app that uses C++ backend app for calculations. Server is running on linux and I use shell_exec for C++ program execution. I updated version of my C++ app and since then shell_exec doesn't work, but
I've checked both versions of C++ app have 777 rights
Both versions run flawlessly from a console
Both versions were tested for same data
Both versions were tested on two different PCs/webservers with same results
For both versions the webapp PHP frontend is exactly the same
Second version (that can't be launched) runs faster then previous one
Questions
Have you ever experienced a similar problem?
Is it possible that in shell_exec a problem could occur, that during standard execution from console doesn't?
Piece of PHP code
class LauncherManager extends Nette\Object {
private $wwwDir;
private $db;
private $f;
public function __construct($wwwDir, \DibiConnection $db) {
$this->wwwDir = $wwwDir;
$this->db = $db;
$this->f = (new Dao\DaoFactory())->setDb($db);
}
public function execMeasurement($measurementId) {
$this->execGenetrac(" -m $measurementId");
}
public function execSamples($analysisId) {
$this->execGenetrac(" -s $analysisId");
}
public function execAnalysis($analysisId) {
$this->execGenetrac(" -a $analysisId");
}
public function execGenetrac($params) {
// Check path to genetrac can be set
$path = $this->wwwDir . "/genetrac";
$this->checkPathExist($path);
// Check library path
$lib = './lib';
$expl = 'export LD_LIBRARY_PATH="' . $lib . '"';
$this->checkPathExist($path . "/" . $lib);
// Check genetrac executable exist
$this->checkPathExist($path . "/genetrac");
// Launch genetrac with parameters
$this->exec("cd $path; $expl; ./genetrac $params");
}
public function exec($command) {
return shell_exec($command);
}
...
shell_exec returns NULL in two situations:
an error occurs
executed program returns no output
In order to distinguish these situations use exec() instead:
public function exec($command) {
exec($command, $arrOutputLines, $intReturnStatus);
return join("", $arrOutputLines);
}
You can debug this code by var_dump'ing $arrOutputLines and $intReturnStatus (these are the array of lines that your program printed out and the numeric exit status of your program (0 usually means OK, non-zero means error)).

PHPUnit with selenium

I am trying to use PHPUnit with selenium
I start the server
java -jar c:/xampp/selenium-server-standalone-2.18.0.jar
This is my test
require_once 'PHPUnit/Extensions/Selenium2TestCase.php';
class WebTest extends PHPUnit_Extensions_Selenium2TestCase {
protected function setUp() {
$this->setBrowser("*chrome");
$this->setBrowserUrl("http://localhost/");
}
public function testMyTestCase() {
$this->url('my/url/index.php');
$link = $this->byId('1-m-0');
$this->assertEquals('11', $link->text());
}
}
Item with id="1-m-0" exists on page, but test fails cause it gets element as null.
I have tried with other elements, SeleniumTestCase class (with the same server) but not luck !
What i do wrong?
Ok, found it out. Here is my class now :
class WebTest extends PHPUnit_Extensions_SeleniumTestCase {
protected function setUp() {
$this->setBrowser("*firefox");
$this->setBrowserUrl("http://localhost/");
}
public function testPlay() {
$this->open('http://localhost/my/url/index.php');
$this->waitForPageToLoad(4000);
// Wait for ajax to load
$this->waitForCondition("selenium.browserbot.getCurrentWindow().$('#mytable').length > 0");
$ids = array(
'1-m-0',
'2-n-1',
);
// Click ids
foreach ($ids as $v) {
$xpath = "xpath=//button[#id='{$v}']";
$this->assertElementPresent($xpath);
$this->click($xpath);
}
}
}
This article helped me:
http://devzone.zend.com/1014/acceptance-testing-of-web-applications-with-php/
I m using this selenium server: selenium-server-standalone-2.18.0.jar
In case you find the phpunit library a little bit confusing we created a library that interacts with the Selenium Json Wire Protocol but we aimed to make it as similar as possible with the official documentation examples. So an example from the selenium site in Java would have nearly the same syntax in php.
Check it out: https://github.com/Nearsoft/PHP-SeleniumClient
If you like it share it, get involved, fork it or do as you please :)
Regards, Mark.

Categories