Giter Club home page Giter Club logo

psyshbundle's Introduction

PsyshBundle

Package version Build Status Scrutinizer Code Quality License

A bundle to use the php REPL PsySH with Symfony. Learn more at psysh.org and check out the Interactive Debugging in PHP talk from OSCON on Presentate.

What does it do exactly?

  • Loads PsySH with the application dependencies
  • Gives access to the following variables:
Variable Description
$container Instance of Symfony ServiceContainer
$kernel Instance of Symfony Kernel
$parameters Instance of Symfony parameters

Aside from that it's the plain old PsySH! You can also customize it to add your own variables.

Documentation

  1. Install
  2. Usage
    1. PsySH as a debugger
    2. Reflect like a boss
    3. PsySH for breakpoints
  3. Customize PsySH
  4. Credits

Install

You can use Composer to install the bundle to your project:

composer require --dev theofidry/psysh-bundle

Then, enable the bundle by updating your app/AppKernel.php file to enable the bundle:
(not needed on symfony 5, bundle is automaticaly registred in config/bundles.php)

<?php
// app/AppKernel.php

public function registerBundles()
{
    //...

    if (in_array($this->getEnvironment(), ['dev', 'test'])) {
        //...
        $bundles[] = new Fidry\PsyshBundle\PsyshBundle();
    }

    return $bundles;
}

Usage

# Symfony > 4.0
bin/console psysh

or

use function psysh

class X
{
    function foo()
    {
        psysh(get_defined_vars(), $this);   // Debug with the current context
    }
}

PsySH Shell

Go further.

Customize PsySH

Adding a custom command

Adding a custom command for PsySH is as simple as defining a service with psysh.command tag!

services:
    my_psysh_command:
        class: Acme\Shell\MyCommand
        tags:
            - { name: psysh.command }

Or even simpler if you use Symfony 3.3+:

services:
    _defaults:
        autoconfigure: true
        autowire: true
        public: false

    Acme\Shell\MyCommand: ~

PsyshBundle provides autoconfiguration for custom Psysh command services, as long as they inherit from Psy\Command\ReflectingCommand or Psy\Command\Command.

Adding custom variables

It is possible to add custom variables to the shell via configuration. Variables can be of any type, container parameters references (e.g. %kernel.debug%) or even services (prefixed with @, e.g. "@my_service").

# app/config/config_dev.yml

psysh:
    variables:
        foo: bar
        router: "@router"
        some: [thing, else]
        debug: "%kernel.debug%"

Now if you run php app/console psysh and then ls, you will see the variables $foo, $router, $some and $debug, in addition to already defined variables:

>>> ls
Variables: $foo, $router, $some, $debug...

Default variables are:

  • $container (the service container)
  • $kernel
  • $parameters (all container parameters)
  • $self (the PsySH shell itself)

Credits

This bundle is developed by Théo FIDRY. This project has been made possible thanks to:

psyshbundle's People

Contributors

chris53897 avatar dlancea avatar lolautruche avatar maxhelias avatar mihaileu avatar msheakoski avatar navitronic avatar nek- avatar oradwell avatar rainbow-alex avatar roverwolf avatar sebsept avatar soullivaneuh avatar theofidry avatar vanputten avatar yched avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

psyshbundle's Issues

Symfony 5.4 custom variables configuration

Are there any updated examples of how to configure custom variables when using slightly newer versions of Symfony, e.g. 5.4? The example provided in the documentation does not seem to work.

Wrong config to Symfony 4.3

I received this error message

TypeError: Argument 1 passed to Symfony\Bundle\FrameworkBundle\Test\WebTestCase::getClient() must be an instance of Symfony\Bundle\FrameworkBundle\KernelBrowser or null, instance of Symfony\Bundle\FrameworkBundle\Client given, called in /app/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php on line 55

And I found a problem we receive 'Symfony\Bundle\FrameworkBundle\Client', but we need KernelBrowser

private static function getClient(KernelBrowser $newClient = null): ?KernelBrowser

And Symfony points to KernelBrowser
But you points to Client

I remove you test.client in my project, and now all works good, please, check this.

Usage examples

Hi there,

I was looking for more in-depth documentation, a wiki page, or other usage examples. I've searched StackOverflow for the bundle's name and looked at closed issues, but I couldn't find any more help on how to use this package apart from the seemingly old screenshot included in the readme.
I come from a Laravel background and my goal is to find a suitable alternative for Laravel artisan tinker in Symfony.

How can I access my application's code in PsyshBundle?
Here are my tries in the console. I obviously have a User entity and plenty of repositories, but it seems I cannot access or even locate them. Could you please help me with some configuration and usage examples?

bin/console psysh
<aside>Psy Shell v0.10.12 (PHP 7.4.26 — cli) by Justin Hileman</aside>
New version is available (current: v0.10.12, latest: v0.11.4)
>>> $container;
=> Symfony\Bundle\FrameworkBundle\Test\TestContainer {#909}
>>> $user = new User();
PHP Error:  Class 'User' not found in Psy Shell code on line 1
>>> $container->get(EntityManagerInterface::class);
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with message 'You have requested a non-existent service "EntityManagerInterface".'
>>> $container->get('doctrine')->getManager();
=> EntityManager_9a5be93 - Doctrine\ORM\EntityManager@proxy {#3016}
>>> $em = $container->get('doctrine')->getManager();
=> EntityManager_9a5be93 - Doctrine\ORM\EntityManager@proxy {#3016}
>>> $em->getRepository('UserRepository');
Doctrine\Persistence\Mapping\MappingException with message 'Class 'UserRepository' does not exist'
>>> $em->getRepository('App:Repository:UserRepository');
Doctrine\ORM\Exception\UnknownEntityNamespace with message 'Unknown Entity namespace alias "App"'
>>> $em->getRepository('App\Repository\UserRepository');
Doctrine\Persistence\Mapping\MappingException with message 'The class 'App\Repository\UserRepository' was not found in the chain configured namespaces App\Entity, Money'
>>> $em->getRepository('\User');
Doctrine\Persistence\Mapping\MappingException with message 'Class '\User' does not exist'
>>> $em->getRepository('User');
Doctrine\Persistence\Mapping\MappingException with message 'Class 'User' does not exist'
>>> $em->list();
PHP Error:  Call to undefined method EntityManager_9a5be93::list() in Psy Shell code on line 1
>>> help
RuntimeException with message 'Too many arguments, expected arguments "command" "command_name".'
>>> $em
=> EntityManager_9a5be93 - Doctrine\ORM\EntityManager@proxy {#3016}

Help command doesn't work

The symfony output interface lacks the page method which breaks the help command, need to use ShellOutput

<aside>Psy Shell v0.10.6 (PHP 7.4.12 — cli) by Justin Hileman</aside>
>>> help ls
PHP Error:  Call to undefined method Symfony\Component\Console\Output\ConsoleOutput::page() in /var/www/app-bi/vendor/psy/psysh/src/Command/HelpCommand.php on line 65

Tested on symfony 5.2 and 4.4

PsySH for breakpoints

Start manually sounds not really nice - is their no other option? Maybe a workaround with a script that run in the background?

What you think? :-)

symfony 3.4 deprecation notice

User Deprecated: The "psysh.facade" service is private, getting it from the container is deprecated since Symfony 3.2 and will fail in 4.0. You should either make the service public, or stop using the container directly and use dependency injection instead. {"exception":"[object] (ErrorException(code: 0): User Deprecated: The \"psysh.facade\" service is private, getting it from the container is deprecated since Symfony 3.2 and will fail in 4.0. You should either make the service public, or stop using the container directly and use dependency injection instead. at vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Container.php:275)"} {"uid":"a789e5a"}

[RFC] Build container with public services

Hello guys. First thanks for this nice bundle :) .

This is about providing a new idea for the bundle, I don't know how to do it but it would be useful.

  • Context: In Symfony4, all services are private by default
  • Problem: if you try to access a service via the container injected into psysh you'll get an error: you can't test your services in psysh anymore
  • Solution: services must be public inside psysh, in order to allow the developer to debug/use services (it should be at least an option available in the configuration of the bundle)

What do you think about? Any idea of how to implement this?

Symfony 5.3 : PsyshCommand should return 0 instead of null

On symfony 5.3, the console prints the following error when leaving the REPL :

12:53:40 CRITICAL  [console] Error thrown while running command "psysh". Message: "Return value of "Fidry\PsyshBundle\Command\PsyshCommand::execute()" must be of the type int, "null" returned." ["exception" => TypeError { …},"command" => "psysh","message" => "Return value of "Fidry\PsyshBundle\Command\PsyshCommand::execute()" must be of the type int, "null" returned."] ["app_name" => "purge","app_environment" => "local"]

In Command.php line 302:
                                                                                   
  Return value of "Fidry\PsyshBundle\Command\PsyshCommand::execute()" must be of   
  the type int, "null" returned.                                                   
                                                                                   

psysh

ERROR: 255

Nothing too serious, since this is just when leaving the session, but clutters the consolle output

Use case with DunglasApiBundle

As of now it is not possible to install this bundle with dunglas/DunglasApiBundle due to dependency conflicts.

Example with api-platform.

$ composer require --dev theofidry/psysh
Using version ^0.2.0 for theofidry/psysh
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for theofidry/psysh ^0.2.0 -> satisfiable by theofidry/psysh[v0.2].
    - Conclusion: remove nikic/php-parser v0.9.5
    - Conclusion: don't install nikic/php-parser v0.9.5
    - theofidry/psysh v0.2 requires psy/psysh 0.4.* -> satisfiable by psy/psysh[v0.4.0, v0.4.1, v0.4.2, v0.4.3, v0.4.4].
    - psy/psysh v0.4.0 requires nikic/php-parser ~1.0 -> satisfiable by nikic/php-parser[v1.0.0, v1.0.1, v1.0.2, v1.1.0, v1.2.0, v1.2.1, v1.2.2, v1.3.0].
    - psy/psysh v0.4.1 requires nikic/php-parser ~1.0 -> satisfiable by nikic/php-parser[v1.0.0, v1.0.1, v1.0.2, v1.1.0, v1.2.0, v1.2.1, v1.2.2, v1.3.0].
    - psy/psysh v0.4.2 requires nikic/php-parser ~1.0 -> satisfiable by nikic/php-parser[v1.0.0, v1.0.1, v1.0.2, v1.1.0, v1.2.0, v1.2.1, v1.2.2, v1.3.0].
    - psy/psysh v0.4.3 requires nikic/php-parser ~1.0 -> satisfiable by nikic/php-parser[v1.0.0, v1.0.1, v1.0.2, v1.1.0, v1.2.0, v1.2.1, v1.2.2, v1.3.0].
    - psy/psysh v0.4.4 requires nikic/php-parser ~1.0 -> satisfiable by nikic/php-parser[v1.0.0, v1.0.1, v1.0.2, v1.1.0, v1.2.0, v1.2.1, v1.2.2, v1.3.0].
    - Can only install one of: nikic/php-parser[v1.0.0, v0.9.5].
    - Can only install one of: nikic/php-parser[v1.0.1, v0.9.5].
    - Can only install one of: nikic/php-parser[v1.0.2, v0.9.5].
    - Can only install one of: nikic/php-parser[v1.1.0, v0.9.5].
    - Can only install one of: nikic/php-parser[v1.2.0, v0.9.5].
    - Can only install one of: nikic/php-parser[v1.2.1, v0.9.5].
    - Can only install one of: nikic/php-parser[v1.2.2, v0.9.5].
    - Can only install one of: nikic/php-parser[v1.3.0, v0.9.5].
    - Installation request for nikic/php-parser == 0.9.5.0 -> satisfiable by nikic/php-parser[v0.9.5].


Installation failed, reverting ./composer.json to its original content.

Project status/ownership

This project was one of my first open source project when I started as a developer. This was based on https://github.com/navitronic/psymf and filled a need of being able to inspect services in Symfony and to use them, as you do in Laravel with Tinker.

Since then a lot of things changed in Symfony:

  • The system around the service locator changed, inlining most services which makes this bundle work a bit funky
  • A debug config & container command was introduced
  • More details of the services are available via the Container XML dump

I also was never fully satisfied with it as I couldn't work out how to get a tab automcompletion like Tinker.

I admit I also very used it for quite a few years now. Somehow I always found more convenient to use a tiny script or Xdebug step-debug mode. The only thing I missing can be provided by https://github.com/phpyh/service-dumper-bundle and this missing feature.

For this reason I would like to officially abandon this project. Since it appears some people are still using it, I guess the question is whether:

  1. This project should be archived, eventually pointing to a new maintained fork.
  2. Hand over the ownership of the project to someone willing to maintain it.

Thoughts?

/cc @wayne530, @aszenz as recent contributors

Symfony 7 support

I get these deprecation's from Symfony 6.4:

  • Method "Symfony\Component\Console\Application::configureIO()" might add "void" as a native return type declaration in the future. Do the same in child class "Psy\Shell" now to avoid errors or add an explicit @return annotation to suppress this message.
  • The "Fidry\PsyshBundle\PsyshFacade" class implements "Symfony\Component\DependencyInjection\ContainerAwareInterface" that is deprecated since Symfony 6.4, use dependency injection instead.

Update doc

Customizing Psysh should be put in the readme, and the doc should escape @

Executing bootstrap process after variable initialization

Hi,

Is there a way to execute code using pre-configured variables like $container each time the shell starts?

One of the scenario's I'd like to achieve on entering the shell is:

$entityManager = $container->get(\Doctrine\ORM\EntityManagerInterface::class);
$user = $entityManager->find(\App\Entity\User::class, 1);
$storage = $container->get('security.token_storage');

$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken(
    $user,
    $user->getPassword(),
    'main',
    $user->getRoles()
);
$storage->setToken($token);

Q: how to refresh code?

Hi
When I changed the method body and call this method from psysh - I get results like from the old code.

Example:

function foo() {echo 'foo';}

(psysh): foo();
(psysh): foo

Then I change the func: function foo() {echo 'bar';}

But:

(psysh): foo();
(psysh): foo // <---- Still the same

What did I do wrong? I try unset and cache clean, but the code refreshed only when psysh is restarted.

Note:

  • symfony project is running in docker.
  • when call show foo - the code is fresh and actual.

psysh is not properly formatting tags (4.3.0)

Hi! I've been struggling with the latest version of this bundle because is not properly formatting the tags, as shown here:

Screenshot from 2020-11-11 16-27-15

As you can see, html tags are not formatted properly, and it also applies when I run ls command and other functionalities.

I'm running it in a php7.3 container.
It could be a psysh problem rather than an issue of this project, so to verify it I made a custom command
that used Psy directly rather than using the command that provides this bundle:

<?php
namespace App\Common\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use function Psy\debug;

class PsyCommand extends Command
{
    protected function configure()
    {
        $this->setName('hat:psysh');
        $this->setDescription('Launch an interactive php shell with Symfony loaded');
        $this->setHelp('Syntax: php bin/console hat:psysh');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $application = $this->getApplication();
        $container = $application->getKernel()->getContainer();
        $kernel = $application->getKernel();
        $parameters = $container->getParameterBag()->all();
        $application->setCatchExceptions(false);
        $application->setAutoExit(false);

        // Seems like less has a problem in the docker image
        debug(get_defined_vars(), get_called_class());
        // Type `help` or `?` in the console to see the available commands
    }
}

So when I run bin/console hat:psysh I get this result:
Screenshot from 2020-11-11 16-44-49

Which seems that is working properly.

Could you bring some light here @theofidry?
Let me know if there's any extra information you need, thanks in advance!

Return type violation in PsyshCommand::execute()

Psy Shell v0.9.12 (PHP 7.4.2 — cli) by Justin Hileman
New version is available (current: v0.9.12, latest: v0.10.0)
>>> quit
Exit:  Goodbye

In Command.php line 258:
                                                                               
  Return value of "Fidry\PsyshBundle\Command\PsyshCommand::execute()" must be  
   of the type int, NULL returned.  

jakub-onderka packages are abandoned

When running composer install, the following messages appear:

Package jakub-onderka/php-console-color is abandoned, you should avoid using it. Use php-parallel-lint/php-console-color instead.
Package jakub-onderka/php-console-highlighter is abandoned, you should avoid using it. Use php-parallel-lint/php-console-highlighter instead.

Allow for psy/psysh v0.6

The composer.json is behind in keeping up with the current psy/psysh version.

Since this is a development only package, I think it makes sense that the psy/psysh version required for this bundle be less restrictive, so that the current version of psy/psysh could keep in pace with this bundle. Something like "^0.5" would be good.

eval with PsySH instance

When using the eval is currently a fresh PsySH instance instead of the one used for the command.

Failed

Hey,
I tried your Bundle, because I wish also inline psysh with Symfony2, but unfortunately it failed by calling the cmd: php app/console psysh. See below.

Any idea, how I can fix that? Thank you in advance. :-)

  [InvalidArgumentException]
  Command "psysh" is not defined.

You have requested a non-existent service "psysh.facade".

docker-compose exec -u app --env SYMFONY_ENV=prod --env SYMFONY_DEBUG=0 php composer install --no-dev -vvv

Generating optimized autoload files
> post-install-cmd: @symfony-scripts
> symfony-scripts: Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
> symfony-scripts: Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache

In Container.php line 348:

  You have requested a non-existent service "psysh.facade".


Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the symfony-scripts event terminated with an exception


  [RuntimeException]
  An error occurred when executing the "'cache:clear --no-warmup'" command:




  In Container.php line 348:

    You have requested a non-existent service "psysh.facade".


Exception trace:
 () at /var/www/app/current/vendor/sensio/distribution-bundle/Composer/ScriptHandler.php:293
 Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::executeCommand() at /var/www/app/current/vendor/sensio/distribution-bundle/Composer/ScriptHandler.php:143
 Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:292
 Composer\EventDispatcher\EventDispatcher->executeEventPhpScript() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:215
 Composer\EventDispatcher\EventDispatcher->doDispatch() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:81
 Composer\EventDispatcher\EventDispatcher->dispatch() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:195
 Composer\EventDispatcher\EventDispatcher->doDispatch() at phar:///usr/bin/composer/src/Composer/EventDispatcher/EventDispatcher.php:96
 Composer\EventDispatcher\EventDispatcher->dispatchScript() at phar:///usr/bin/composer/src/Composer/Installer.php:323
 Composer\Installer->run() at phar:///usr/bin/composer/src/Composer/Command/InstallCommand.php:119
 Composer\Command\InstallCommand->execute() at phar:///usr/bin/composer/vendor/symfony/console/Command/Command.php:242
 Symfony\Component\Console\Command\Command->run() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:843
 Symfony\Component\Console\Application->doRunCommand() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:193
 Symfony\Component\Console\Application->doRun() at phar:///usr/bin/composer/src/Composer/Console/Application.php:251
 Composer\Console\Application->doRun() at phar:///usr/bin/composer/vendor/symfony/console/Application.php:117
 Symfony\Component\Console\Application->run() at phar:///usr/bin/composer/src/Composer/Console/Application.php:100
 Composer\Console\Application->run() at phar:///usr/bin/composer/bin/composer:59
 require() at /usr/bin/composer:24

install [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [--no-suggest] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--ignore-platform-reqs] [--] [<packages>]...

composer.json

        "psy/psysh": "^0.9.7",
        "theofidry/psysh-bundle": "^3.5",

composer info

psy/psysh                              v0.9.9            An interactive shell for modern PHP.
theofidry/psysh-bundle                 v3.5.0            A port of the PHP REPL PsySH for Symfony.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.