master 431ce296028d cached
22 files
25.2 KB
6.4k tokens
38 symbols
1 requests
Download .txt
Repository: beyondcode/laravel-tinker-server
Branch: master
Commit: 431ce296028d
Files: 22
Total size: 25.2 KB

Directory structure:
gitextract_1ydr43zu/

├── .editorconfig
├── .gitattributes
├── .gitignore
├── .scrutinizer.yml
├── .styleci.yml
├── .travis.yml
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── composer.json
├── config/
│   └── config.php
├── phpunit.xml.dist
├── src/
│   ├── Connection.php
│   ├── Console/
│   │   └── TinkerServerCommand.php
│   ├── LaravelTinkerServerServiceProvider.php
│   ├── Server.php
│   ├── Shell/
│   │   └── ExecutionClosure.php
│   └── helpers.php
└── tests/
    ├── ConnectionTest.php
    ├── EchoStream.php
    └── fixtures/
        └── server.php

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org

root = true

[*]
charset = utf-8
indent_size = 4
indent_style = space
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false


================================================
FILE: .gitattributes
================================================
# Path-based git attributes
# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html

# Ignore all test and documentation with "export-ignore".
/.gitattributes     export-ignore
/.gitignore         export-ignore
/.travis.yml        export-ignore
/phpunit.xml.dist   export-ignore
/.scrutinizer.yml   export-ignore
/tests              export-ignore
/.editorconfig      export-ignore


================================================
FILE: .gitignore
================================================
build
composer.lock
docs
vendor
coverage

================================================
FILE: .scrutinizer.yml
================================================
filter:
    excluded_paths: [tests/*]

checks:
    php:
        remove_extra_empty_lines: true
        remove_php_closing_tag: true
        remove_trailing_whitespace: true
        fix_use_statements:
            remove_unused: true
            preserve_multiple: false
            preserve_blanklines: true
            order_alphabetically: true
        fix_php_opening_tag: true
        fix_linefeed: true
        fix_line_ending: true
        fix_identation_4spaces: true
        fix_doc_comments: true



================================================
FILE: .styleci.yml
================================================
preset: laravel

disabled:
  - single_class_element_per_statement


================================================
FILE: .travis.yml
================================================
language: php

php:
  - 7.1
  - 7.2
  - 7.3

before_script:
  - travis_retry composer self-update
  - travis_retry composer update --no-interaction

script:
  - vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover

after_script:
  - php vendor/bin/ocular code-coverage:upload --format=php-clover coverage.clover


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to `laravel-tinker-server` will be documented in this file

## 1.0.0 - 201X-XX-XX

- initial release


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing

Contributions are **welcome** and will be fully **credited**.

Please read and understand the contribution guide before creating an issue or pull request.

## Etiquette

This project is open source, and as such, the maintainers give their free time to build and maintain the source code
held within. They make the code freely available in the hope that it will be of use to other developers. It would be
extremely unfair for them to suffer abuse or anger for their hard work.

Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
world that developers are civilized and selfless people.

It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.

## Viability

When requesting or submitting new features, first consider whether it might be useful to others. Open
source projects are used by many developers, who may have entirely different needs to your own. Think about
whether or not your feature is likely to be used by other users of the project.

## Procedure

Before filing an issue:

- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
- Check to make sure your feature suggestion isn't already present within the project.
- Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
- Check the pull requests tab to ensure that the feature isn't already in progress.

Before submitting a pull request:

- Check the codebase to ensure that your feature doesn't already exist.
- Check the pull requests to ensure that another person hasn't already submitted the feature or fix.

## Requirements

If the project maintainer has any additional requirements, you will find them listed here.

- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).

- **Add tests!** - Your patch won't be accepted if it doesn't have tests.

- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.

- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.

- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.

- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.

**Happy coding**!


================================================
FILE: LICENSE.md
================================================
MIT License

Copyright (c) Marcel Pociot

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

================================================
FILE: README.md
================================================
# Laravel Tinker Server

[![Latest Version on Packagist](https://img.shields.io/packagist/v/beyondcode/laravel-tinker-server.svg?style=flat-square)](https://packagist.org/packages/beyondcode/laravel-tinker-server)
[![Build Status](https://img.shields.io/travis/beyondcode/laravel-tinker-server/master.svg?style=flat-square)](https://travis-ci.org/beyondcode/laravel-tinker-server)
[![Quality Score](https://img.shields.io/scrutinizer/g/beyondcode/laravel-tinker-server.svg?style=flat-square)](https://scrutinizer-ci.com/g/beyondcode/laravel-tinker-server)
[![Total Downloads](https://img.shields.io/packagist/dt/beyondcode/laravel-tinker-server.svg?style=flat-square)](https://packagist.org/packages/beyondcode/laravel-tinker-server)

This package will give you a tinker server, that collects all your `tinker` call outputs **and** allows you to interact with the variables on the fly.

![](https://beyondco.de/github/tinker-server/tinker-server-demo.gif)

## About this package

This package was built as part of my [PHP Package Development](https://phppackagedevelopment.com) video course. Register for the course to learn how this package was built.

## Installation

You can install the package via composer:

```bash
composer require beyondcode/laravel-tinker-server
```

The package will register itself automatically.

Optionally you can publish the package configuration using:

```bash
php artisan vendor:publish --provider=BeyondCode\\LaravelTinkerServer\\LaravelTinkerServerServiceProvider
```

This will publish a file called `laravel-tinker-server.php` in your `config` folder.

In the config file, you can specify the dump server host that you want to listen on, in case you want to change the default value.

## Usage

Start the tinker server by calling the artisan command:

```bash
php artisan tinker-server
```

And then you can put `tinker` calls in your methods to dump variable content as well as instantly making them available in an interactive REPL shell.

```php
$user = App\User::find(1);

tinker($user);
```

In addition to the `tinker` method, there is also a `td` method, that behaves similar to `dd`. It tinkers the variable and dies the current request.

### Testing

``` bash
composer test
```

### Changelog

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

If you discover any security related issues, please email marcel@beyondco.de instead of using the issue tracker.

## Credits

- [Marcel Pociot](https://github.com/mpociot)
- [All Contributors](../../contributors)

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

## Laravel Package Boilerplate

This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com).


================================================
FILE: composer.json
================================================
{
    "name": "beyondcode/laravel-tinker-server",
    "description": "Tinker with your variables while working on your application.",
    "keywords": [
        "beyondcode",
        "laravel-tinker-server"
    ],
    "homepage": "https://github.com/beyondcode/laravel-tinker-server",
    "license": "MIT",
    "type": "library",
    "authors": [
        {
            "name": "Marcel Pociot",
            "email": "marcel@beyondco.de",
            "role": "Developer"
        }
    ],
    "require": {
        "php": "^7.1",
        "clue/stdio-react": "^2.2",
        "illuminate/support": "5.6.*|5.7.*|5.8.*|6.*",
        "laravel/tinker": "^1.0",
        "psy/psysh": "^0.9.9",
        "react/socket": "^1.2"
    },
    "require-dev": {
        "orchestra/testbench": "3.7.*",
        "phpunit/phpunit": "^7.0"
    },
    "autoload": {
        "files": [
            "src/helpers.php"
        ],
        "psr-4": {
            "BeyondCode\\LaravelTinkerServer\\": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "BeyondCode\\LaravelTinkerServer\\Tests\\": "tests"
        }
    },
    "scripts": {
        "test": "vendor/bin/phpunit",
        "test-coverage": "vendor/bin/phpunit --coverage-html coverage"

    },
    "config": {
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "providers": [
                "BeyondCode\\LaravelTinkerServer\\LaravelTinkerServerServiceProvider"
            ]
        }
    }
}


================================================
FILE: config/config.php
================================================
<?php

return [
    /*
     * The host to use when listening for debug server connections.
     */
    'host' => 'tcp://127.0.0.1:9914',
];


================================================
FILE: phpunit.xml.dist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
         backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         verbose="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory suffix=".php">src/</directory>
        </whitelist>
    </filter>
    <logging>
        <log type="tap" target="build/report.tap"/>
        <log type="junit" target="build/report.junit.xml"/>
        <log type="coverage-html" target="build/coverage"/>
        <log type="coverage-text" target="build/coverage.txt"/>
        <log type="coverage-clover" target="build/logs/clover.xml"/>
    </logging>
</phpunit>


================================================
FILE: src/Connection.php
================================================
<?php

namespace BeyondCode\LaravelTinkerServer;

class Connection
{
    protected $socket;

    protected $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function write(array $namedParameters): bool
    {
        if (! $this->socket = $this->socket ?: $this->createSocket()) {
            return false;
        }

        set_error_handler([self::class, 'nullErrorHandler']);

        try {
            $encodedPayload = base64_encode(serialize($namedParameters))."\n";

            if (-1 !== stream_socket_sendto($this->socket, $encodedPayload)) {
                return true;
            }

            stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
            fclose($this->socket);
            $this->socket = $this->createSocket();

            if (-1 !== stream_socket_sendto($this->socket, $encodedPayload)) {
                return true;
            }
        } finally {
            restore_error_handler();
        }

        return false;
    }

    private static function nullErrorHandler($t, $m)
    {
        // no-op
    }

    private function createSocket()
    {
        set_error_handler([self::class, 'nullErrorHandler']);
        try {
            return stream_socket_client($this->host, $errno, $errstr, 3, STREAM_CLIENT_CONNECT);
        } finally {
            restore_error_handler();
        }
    }
}


================================================
FILE: src/Console/TinkerServerCommand.php
================================================
<?php

namespace BeyondCode\LaravelTinkerServer\Console;

use BeyondCode\LaravelTinkerServer\Server;
use Illuminate\Console\Command;
use Laravel\Tinker\ClassAliasAutoloader;
use Psy\Configuration;
use Psy\Shell;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Output\BufferedOutput;

class TinkerServerCommand extends Command
{
    protected $signature = 'tinker-server';

    public function handle()
    {
        $output = $this->createWarningFormatter();

        $server = new Server(config('laravel-tinker-server.host'), $this->createPsyShell(), $output);

        $server->start();
    }

    protected function createWarningFormatter(): BufferedOutput
    {
        $output = new BufferedOutput();

        if (! $output->getFormatter()->hasStyle('warning')) {
            $style = new OutputFormatterStyle('yellow');

            $output->getFormatter()->setStyle('warning', $style);
        }

        return $output;
    }

    protected function createPsyShell()
    {
        $config = new Configuration([
            'updateCheck' => 'never',
        ]);

        $config->getPresenter()->addCasters(
            $this->getCasters()
        );

        $shell = new Shell($config);

        $path = $this->getLaravel()->basePath().DIRECTORY_SEPARATOR.'vendor/composer/autoload_classmap.php';

        ClassAliasAutoloader::register($shell, $path);

        return $shell;
    }

    protected function getCasters()
    {
        $casters = [
            'Illuminate\Support\Collection' => 'Laravel\Tinker\TinkerCaster::castCollection',
        ];
        if (class_exists('Illuminate\Database\Eloquent\Model')) {
            $casters['Illuminate\Database\Eloquent\Model'] = 'Laravel\Tinker\TinkerCaster::castModel';
        }
        if (class_exists('Illuminate\Foundation\Application')) {
            $casters['Illuminate\Foundation\Application'] = 'Laravel\Tinker\TinkerCaster::castApplication';
        }

        return $casters;
    }
}


================================================
FILE: src/LaravelTinkerServerServiceProvider.php
================================================
<?php

namespace BeyondCode\LaravelTinkerServer;

use BeyondCode\LaravelTinkerServer\Console\TinkerServerCommand;
use Illuminate\Support\ServiceProvider;

class LaravelTinkerServerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__.'/../config/config.php' => config_path('laravel-tinker-server.php'),
            ], 'config');

            // Registering package commands.
            $this->commands([
                TinkerServerCommand::class,
            ]);
        }
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        // Automatically apply the package configuration
        $this->mergeConfigFrom(__DIR__.'/../config/config.php', 'laravel-tinker-server');
    }
}


================================================
FILE: src/Server.php
================================================
<?php

namespace BeyondCode\LaravelTinkerServer;

use BeyondCode\LaravelTinkerServer\Shell\ExecutionClosure;
use Clue\React\Stdio\Stdio;
use Psy\Shell;
use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
use React\Socket\ConnectionInterface;
use React\Socket\Server as SocketServer;
use Symfony\Component\Console\Output\BufferedOutput;

class Server
{
    protected $host;

    /** @var LoopInterface */
    protected $loop;

    /** @var BufferedOutput */
    protected $shellOutput;

    /** @var Shell */
    protected $shell;

    /** @var BufferedOutput */
    protected $output;

    /** @var Stdio */
    protected $stdio;

    public function __construct($host, Shell $shell, BufferedOutput $output, LoopInterface $loop = null, Stdio $stdio = null)
    {
        $this->host = $host;
        $this->loop = $loop ?? Factory::create();
        $this->shell = $shell;
        $this->output = $output;
        $this->shellOutput = new BufferedOutput();
        $this->stdio = $stdio ?? $this->createStdio();
    }

    public function start()
    {
        $this->shell->setOutput($this->shellOutput);

        $this->createSocketServer();

        $this->loop->run();
    }

    protected function createSocketServer()
    {
        $socket = new SocketServer($this->host, $this->loop);

        $socket->on('connection', function (ConnectionInterface $connection) {
            $connection->on('data', function ($data) use ($connection) {
                $unserializedData = unserialize(base64_decode($data));

                $this->shell->setScopeVariables(array_merge($unserializedData, $this->shell->getScopeVariables()));

                $this->stdio->write(PHP_EOL);

                collect($unserializedData)->keys()->map(function ($variableName) {
                    $this->output->writeln('>> $'.$variableName);

                    $this->executeCode('$'.$variableName);

                    $this->output->write($this->shellOutput->fetch());

                    $this->stdio->write($this->output->fetch());
                });
            });
        });
    }

    protected function createStdio(): Stdio
    {
        $stdio = new Stdio($this->loop);

        $stdio->getReadline()->setPrompt('>> ');

        $stdio->on('data', function ($line) use ($stdio) {
            $line = rtrim($line, "\r\n");

            $stdio->getReadline()->addHistory($line);

            $this->executeCode($line);

            $this->output->write(PHP_EOL.$this->shellOutput->fetch());

            $this->stdio->write($this->output->fetch());
        });

        return $stdio;
    }

    protected function executeCode($code)
    {
        (new ExecutionClosure($this->shell, $code))->execute();
    }
}


================================================
FILE: src/Shell/ExecutionClosure.php
================================================
<?php

namespace BeyondCode\LaravelTinkerServer\Shell;

use Psy\CodeCleaner\NoReturnValue;
use Psy\Exception\BreakException;
use Psy\Exception\ErrorException;
use Psy\Exception\ThrowUpException;
use Psy\Exception\TypeErrorException;
use Psy\ExecutionClosure as BaseExecutionClosure;
use Psy\Shell;

class ExecutionClosure extends BaseExecutionClosure
{
    public function __construct(Shell $__psysh__, $__line__)
    {
        $this->setClosure($__psysh__, function () use ($__psysh__, $__line__) {
            try {
                try {
                    // Restore execution scope variables
                    \extract($__psysh__->getScopeVariables(false), EXTR_SKIP);

                    $_ = new NoReturnValue();

                    $__psysh__->addCode($__line__);

                    // Convert all errors to exceptions
                    \set_error_handler([$__psysh__, 'handleError']);

                    // Evaluate the current code buffer
                    $_ = eval($__psysh__->onExecute($__psysh__->flushCode() ?: self::NOOP_INPUT));
                } catch (\Throwable $_e) {
                    // Clean up on our way out.
                    \restore_error_handler();

                    throw $_e;
                } catch (\Exception $_e) {
                    // Clean up on our way out.
                    \restore_error_handler();

                    throw $_e;
                }
            } catch (BreakException $_e) {
                $__psysh__->writeException($_e);

                return;
            } catch (ThrowUpException $_e) {
                $__psysh__->writeException($_e);

                throw $_e;
            } catch (\TypeError $_e) {
                $__psysh__->writeException(TypeErrorException::fromTypeError($_e));
            } catch (\Error $_e) {
                $__psysh__->writeException(ErrorException::fromError($_e));
            } catch (\Exception $_e) {
                $__psysh__->writeException($_e);
            }

            \restore_error_handler();

            $__psysh__->writeReturnValue($_);

            // Save execution scope variables for next time
            $__psysh__->setScopeVariables(\get_defined_vars());

            return $_;
        });
    }
}


================================================
FILE: src/helpers.php
================================================
<?php

if (! function_exists('tinker')) {
    function tinker(...$args)
    {
        /*
         * Thank you Caleb
         * See: https://github.com/calebporzio/awesome-helpers/blob/master/src/helpers/tinker.php
         */
        $namedParameters = collect(debug_backtrace())
            ->where('function', 'tinker')->take(1)
            ->map(function ($slice) {
                return array_values($slice);
            })
            ->mapSpread(function ($filePath, $lineNumber, $function, $args) {
                return file($filePath)[$lineNumber - 1];
                // "    tinker($post, new User);"
            })->map(function ($carry) {
                return str_before(str_after($carry, 'tinker('), ');');
                // "$post, new User"
            })->flatMap(function ($carry) {
                return array_map('trim', explode(',', $carry));
                // ["post", "new User"]
            })->map(function ($carry, $index) {
                return strpos($carry, '$') === 0
                    ? str_after($carry, '$')
                    : 'temp'.$index;
                // ["post", "temp1"]
            })
            ->combine($args)->all();

        $connection = new \BeyondCode\LaravelTinkerServer\Connection(config('laravel-tinker-server.host'));

        if (! $connection->write($namedParameters)) {
            dump($args);
        }
    }
}

if (! function_exists('td')) {
    function td(...$args)
    {
        tinker($args);

        die(1);
    }
}


================================================
FILE: tests/ConnectionTest.php
================================================
<?php

namespace BeyondCode\LaravelTinkerServer\Tests;

use BeyondCode\LaravelTinkerServer\Connection;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\PhpProcess;
use Symfony\Component\Process\Process;

class ConnectionTest extends TestCase
{
    const TINKER_SERVER_HOST = 'tcp://127.0.0.1:9914';

    public function testDump()
    {
        $connection = new Connection(self::TINKER_SERVER_HOST);

        $dumped = null;

        $process = $this->getServerProcess();

        try {
            $process->start(function ($type, $buffer) use ($process, &$dumped, $connection) {
                if (Process::ERR === $type) {
                    $process->stop();
                    $this->fail();
                } elseif ("READY\n" === $buffer) {
                    usleep(5000);
                    $result = $connection->write(['i' => 10]);

                    $this->assertTrue($result);
                } else {
                    $dumped .= $buffer;
                }
            });

            $process->wait();
        } catch (ProcessTimedOutException $e) {
            //
        }

        $this->assertSame("\r\e[K
\r\e[K>> \$i
=> 10\n", $dumped);
    }

    /** @test */
    public function it_detects_if_the_tinker_server_is_offline()
    {
        $connection = new Connection(self::TINKER_SERVER_HOST);

        $start = microtime(true);
        $this->assertFalse($connection->write([]));
        $this->assertLessThan(1, microtime(true) - $start);
    }

    protected function getServerProcess(): Process
    {
        $process = new PhpProcess(file_get_contents(__DIR__.'/fixtures/server.php'), null, [
            'COMPONENT_ROOT' => __DIR__.'/../',
            'TINKER_SERVER_HOST' => self::TINKER_SERVER_HOST,
        ]);

        $process->inheritEnvironmentVariables(true);

        return $process->setTimeout(3);
    }
}


================================================
FILE: tests/EchoStream.php
================================================
<?php

namespace BeyondCode\LaravelTinkerServer\Tests;

use React\Stream\WritableStreamInterface;

class EchoStream implements WritableStreamInterface
{
    public function on($event, callable $listener)
    {
        // TODO: Implement on() method.
    }

    public function once($event, callable $listener)
    {
        // TODO: Implement once() method.
    }

    public function removeListener($event, callable $listener)
    {
        // TODO: Implement removeListener() method.
    }

    public function removeAllListeners($event = null)
    {
        // TODO: Implement removeAllListeners() method.
    }

    public function listeners($event = null)
    {
        // TODO: Implement listeners() method.
    }

    public function emit($event, array $arguments = [])
    {
        // TODO: Implement emit() method.
    }

    public function isWritable()
    {
        return true;
    }

    public function write($data)
    {
        echo $data;
    }

    public function end($data = null)
    {
        // TODO: Implement end() method.
    }

    public function close()
    {
        // TODO: Implement close() method.
    }
}


================================================
FILE: tests/fixtures/server.php
================================================
<?php

use BeyondCode\LaravelTinkerServer\Server;
use BeyondCode\LaravelTinkerServer\Tests\EchoStream;
use Psy\Configuration;
use Symfony\Component\Console\Output\BufferedOutput;

$componentRoot = $_SERVER['COMPONENT_ROOT'] ?? __DIR__.'/../..';

$file = $componentRoot.'/vendor/autoload.php';

require $file;

$loop = \React\EventLoop\Factory::create();

$output = new BufferedOutput();

$config = new Configuration([
    'updateCheck' => 'never',
]);

$stdio = new \Clue\React\Stdio\Stdio($loop, null, new EchoStream());

$shell = new \Psy\Shell($config);

$server = new Server(getenv('TINKER_SERVER_HOST'), $shell, $output, $loop, $stdio);

echo "READY\n";

$server->start();
Download .txt
gitextract_1ydr43zu/

├── .editorconfig
├── .gitattributes
├── .gitignore
├── .scrutinizer.yml
├── .styleci.yml
├── .travis.yml
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── composer.json
├── config/
│   └── config.php
├── phpunit.xml.dist
├── src/
│   ├── Connection.php
│   ├── Console/
│   │   └── TinkerServerCommand.php
│   ├── LaravelTinkerServerServiceProvider.php
│   ├── Server.php
│   ├── Shell/
│   │   └── ExecutionClosure.php
│   └── helpers.php
└── tests/
    ├── ConnectionTest.php
    ├── EchoStream.php
    └── fixtures/
        └── server.php
Download .txt
SYMBOL INDEX (38 symbols across 8 files)

FILE: src/Connection.php
  class Connection (line 5) | class Connection
    method __construct (line 11) | public function __construct($host)
    method write (line 16) | public function write(array $namedParameters): bool
    method nullErrorHandler (line 45) | private static function nullErrorHandler($t, $m)
    method createSocket (line 50) | private function createSocket()

FILE: src/Console/TinkerServerCommand.php
  class TinkerServerCommand (line 13) | class TinkerServerCommand extends Command
    method handle (line 17) | public function handle()
    method createWarningFormatter (line 26) | protected function createWarningFormatter(): BufferedOutput
    method createPsyShell (line 39) | protected function createPsyShell()
    method getCasters (line 58) | protected function getCasters()

FILE: src/LaravelTinkerServerServiceProvider.php
  class LaravelTinkerServerServiceProvider (line 8) | class LaravelTinkerServerServiceProvider extends ServiceProvider
    method boot (line 13) | public function boot()
    method register (line 30) | public function register()

FILE: src/Server.php
  class Server (line 14) | class Server
    method __construct (line 33) | public function __construct($host, Shell $shell, BufferedOutput $outpu...
    method start (line 43) | public function start()
    method createSocketServer (line 52) | protected function createSocketServer()
    method createStdio (line 77) | protected function createStdio(): Stdio
    method executeCode (line 98) | protected function executeCode($code)

FILE: src/Shell/ExecutionClosure.php
  class ExecutionClosure (line 13) | class ExecutionClosure extends BaseExecutionClosure
    method __construct (line 15) | public function __construct(Shell $__psysh__, $__line__)

FILE: src/helpers.php
  function tinker (line 4) | function tinker(...$args)
  function td (line 41) | function td(...$args)

FILE: tests/ConnectionTest.php
  class ConnectionTest (line 11) | class ConnectionTest extends TestCase
    method testDump (line 15) | public function testDump()
    method it_detects_if_the_tinker_server_is_offline (line 49) | public function it_detects_if_the_tinker_server_is_offline()
    method getServerProcess (line 58) | protected function getServerProcess(): Process

FILE: tests/EchoStream.php
  class EchoStream (line 7) | class EchoStream implements WritableStreamInterface
    method on (line 9) | public function on($event, callable $listener)
    method once (line 14) | public function once($event, callable $listener)
    method removeListener (line 19) | public function removeListener($event, callable $listener)
    method removeAllListeners (line 24) | public function removeAllListeners($event = null)
    method listeners (line 29) | public function listeners($event = null)
    method emit (line 34) | public function emit($event, array $arguments = [])
    method isWritable (line 39) | public function isWritable()
    method write (line 44) | public function write($data)
    method end (line 49) | public function end($data = null)
    method close (line 54) | public function close()
Condensed preview — 22 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (28K chars).
[
  {
    "path": ".editorconfig",
    "chars": 312,
    "preview": "; This file is for unifying the coding style for different editors and IDEs.\n; More information at http://editorconfig.o"
  },
  {
    "path": ".gitattributes",
    "chars": 395,
    "preview": "# Path-based git attributes\n# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html\n\n# Ignore all test and"
  },
  {
    "path": ".gitignore",
    "chars": 40,
    "preview": "build\ncomposer.lock\ndocs\nvendor\ncoverage"
  },
  {
    "path": ".scrutinizer.yml",
    "chars": 507,
    "preview": "filter:\n    excluded_paths: [tests/*]\n\nchecks:\n    php:\n        remove_extra_empty_lines: true\n        remove_php_closin"
  },
  {
    "path": ".styleci.yml",
    "chars": 66,
    "preview": "preset: laravel\n\ndisabled:\n  - single_class_element_per_statement\n"
  },
  {
    "path": ".travis.yml",
    "chars": 328,
    "preview": "language: php\n\nphp:\n  - 7.1\n  - 7.2\n  - 7.3\n\nbefore_script:\n  - travis_retry composer self-update\n  - travis_retry compo"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 134,
    "preview": "# Changelog\n\nAll notable changes to `laravel-tinker-server` will be documented in this file\n\n## 1.0.0 - 201X-XX-XX\n\n- in"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 2972,
    "preview": "# Contributing\n\nContributions are **welcome** and will be fully **credited**.\n\nPlease read and understand the contributi"
  },
  {
    "path": "LICENSE.md",
    "chars": 1064,
    "preview": "MIT License\n\nCopyright (c) Marcel Pociot\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\no"
  },
  {
    "path": "README.md",
    "chars": 2865,
    "preview": "# Laravel Tinker Server\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/beyondcode/laravel-tinker-se"
  },
  {
    "path": "composer.json",
    "chars": 1480,
    "preview": "{\n    \"name\": \"beyondcode/laravel-tinker-server\",\n    \"description\": \"Tinker with your variables while working on your a"
  },
  {
    "path": "config/config.php",
    "chars": 140,
    "preview": "<?php\n\nreturn [\n    /*\n     * The host to use when listening for debug server connections.\n     */\n    'host' => 'tcp://"
  },
  {
    "path": "phpunit.xml.dist",
    "chars": 995,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit bootstrap=\"vendor/autoload.php\"\n         backupGlobals=\"false\"\n         "
  },
  {
    "path": "src/Connection.php",
    "chars": 1395,
    "preview": "<?php\n\nnamespace BeyondCode\\LaravelTinkerServer;\n\nclass Connection\n{\n    protected $socket;\n\n    protected $host;\n\n    p"
  },
  {
    "path": "src/Console/TinkerServerCommand.php",
    "chars": 2001,
    "preview": "<?php\n\nnamespace BeyondCode\\LaravelTinkerServer\\Console;\n\nuse BeyondCode\\LaravelTinkerServer\\Server;\nuse Illuminate\\Cons"
  },
  {
    "path": "src/LaravelTinkerServerServiceProvider.php",
    "chars": 913,
    "preview": "<?php\n\nnamespace BeyondCode\\LaravelTinkerServer;\n\nuse BeyondCode\\LaravelTinkerServer\\Console\\TinkerServerCommand;\nuse Il"
  },
  {
    "path": "src/Server.php",
    "chars": 2726,
    "preview": "<?php\n\nnamespace BeyondCode\\LaravelTinkerServer;\n\nuse BeyondCode\\LaravelTinkerServer\\Shell\\ExecutionClosure;\nuse Clue\\Re"
  },
  {
    "path": "src/Shell/ExecutionClosure.php",
    "chars": 2244,
    "preview": "<?php\n\nnamespace BeyondCode\\LaravelTinkerServer\\Shell;\n\nuse Psy\\CodeCleaner\\NoReturnValue;\nuse Psy\\Exception\\BreakExcept"
  },
  {
    "path": "src/helpers.php",
    "chars": 1497,
    "preview": "<?php\n\nif (! function_exists('tinker')) {\n    function tinker(...$args)\n    {\n        /*\n         * Thank you Caleb\n    "
  },
  {
    "path": "tests/ConnectionTest.php",
    "chars": 1936,
    "preview": "<?php\n\nnamespace BeyondCode\\LaravelTinkerServer\\Tests;\n\nuse BeyondCode\\LaravelTinkerServer\\Connection;\nuse PHPUnit\\Frame"
  },
  {
    "path": "tests/EchoStream.php",
    "chars": 1142,
    "preview": "<?php\n\nnamespace BeyondCode\\LaravelTinkerServer\\Tests;\n\nuse React\\Stream\\WritableStreamInterface;\n\nclass EchoStream impl"
  },
  {
    "path": "tests/fixtures/server.php",
    "chars": 678,
    "preview": "<?php\n\nuse BeyondCode\\LaravelTinkerServer\\Server;\nuse BeyondCode\\LaravelTinkerServer\\Tests\\EchoStream;\nuse Psy\\Configura"
  }
]

About this extraction

This page contains the full source code of the beyondcode/laravel-tinker-server GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 22 files (25.2 KB), approximately 6.4k tokens, and a symbol index with 38 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!