Full Code of spatie/laravel-tinker-tools for AI

master 6cac407acd79 cached
14 files
13.5 KB
3.7k tokens
9 symbols
1 requests
Download .txt
Repository: spatie/laravel-tinker-tools
Branch: master
Commit: 6cac407acd79
Files: 14
Total size: 13.5 KB

Directory structure:
gitextract_krs3r2ca/

├── .editorconfig
├── .gitattributes
├── .gitignore
├── .scrutinizer.yml
├── .styleci.yml
├── .travis.yml
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│   └── ShortClassNames.php
└── tests/
    ├── NamespacedClass.php
    └── ShortClassNamesTest.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


================================================
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

linting: true

disabled:
  - single_class_element_per_statement


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

php:
  - 7.0
  - 7.1
  - 7.2

env:
  matrix:
    - COMPOSER_FLAGS="--prefer-lowest"
    - COMPOSER_FLAGS=""

before_script:
  - travis_retry composer self-update
  - travis_retry composer update ${COMPOSER_FLAGS} --no-interaction --prefer-source

script:
  - composer dump-autoload -o
  - 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-tools` will be documented in this file

## 1.0.1 - 2017-07-28

- avoid aliasing interfaces

## 1.0.0 - 2017-05-22

- initial release


================================================
FILE: LICENSE.md
================================================
The MIT License (MIT)

Copyright (c) Spatie bvba <info@spatie.be>

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
================================================
**The functionality of this package is built into Laravel 5.5 and above, only install this in older Laravel versions**

# Use short class names in an Artisan Tinker session

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

When using Artisan's Tinker command it can be quite bothersome having to type the fully qualified classname to do something simple.

```php
\App\Models\NewsItem::first();
```

This package contains a class that, when fully installed lets you use the short class names:

```php
NewsItem::first();
```

## Support us

[<img src="https://github-ads.s3.eu-central-1.amazonaws.com/laravel-tinker-tools.jpg?t=1" width="419px" />](https://spatie.be/github-ad-click/laravel-tinker-tools)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

## Installation

First install the package via Composer:

``` bash
composer require spatie/laravel-tinker-tools
```

Next, create a file named `.psysh.php` in the root of your Laravel app with this content:

```php
<?php

\Spatie\TinkerTools\ShortClassNames::register();
```

Finally, dump the optimized version of the autoloader so `autoload_classmap.php` gets created:

```bash
composer dump-autoload -o
```

## Usage

Open up a Tinker session with:

```bash
php artisan tinker
```

Inside that Tinker session you can now use short class names:

```php
NewsItem::first();
```

## A peek behind the curtains

When you use a class that hasn't been loaded in yet, PHP will call the registered autoloader functions. Such autoloader functions are responsible for loading up the requested class. In a typical project Composer will register an autoloader function that can `include` the file where the class is stored in.

Composer has a few ways to locate the right files. In most cases it will convert the fully qualified class name to a path. For example, when using a class `App\Models\NewsItem` Composer will load the file in `app/Models/NewsItem.php`. It's a bit more complicated behind the scenes but that's the gist of it. To make the process of finding a class fast, Composer caches all the fully qualified classnames and their paths in the generated `autoload_classmap.php`, which can be found in `vendor/composer`. 

Now, to make this package work, `\Spatie\TinkerTools\ShortClassNames` will read Composer's `autoload_classmap.php` and [convert the fully qualified class names to short class names](https://github.com/spatie/laravel-tinker-tools/blob/d3a3287/src/ShortClassNames.php#L23). The result is a collection that's being kept in [the `$classes` property](https://github.com/spatie/laravel-tinker-tools/blob/098e595/src/ShortClassNames.php#L8)

Our class will also [register an autoloader](https://github.com/spatie/laravel-tinker-tools/blob/098e595/src/ShortClassNames.php#L33). When you use `NewsItem` in your code. PHP will first call Composer's autoloader. But of course that autoloader can't find the class. So the autoloader from this package comes next. Our autoloader will use the aforementioned `$classes` collection to find to fully qualified class name. It will then [use `class_alias`](https://github.com/spatie/laravel-tinker-tools/blob/098e595/src/ShortClassNames.php#L46) to alias `NewsItem` to `App\Models\NewsItem`.

## What happens if there are multiple classes with same name?

Now you might wonder what'll happen it there are more classes with the same name in different namespaces? E.g. `App\Models\NewsItem`, `Vendor\PackageName\NewsItem`. Well, `autoload_classmap.php` is sorted alphabetically on the fully qualified namespace. So `App\Models\NewsItem` will be used and not `Vendor\PackageName\NewsItem`.

Because `App` starts with an "A" there's a high chance that, in case of a collision, a class inside your application will get picked. Currently there are no ways to alter this. I'd accept PRs that make this behaviour customizable.

## Need more Tinker magic?

There are a lot of other options that can be set in `tinker.config.php`. Learn all the options by reading [the official psysh configuration documentation](http://psysh.org/#configure).

## Changelog

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

## Testing

``` bash
$ composer test
```

## Contributing

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

## Security

If you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.

## Postcardware

You're free to use this package (it's [MIT-licensed](LICENSE.md)), but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

## Credits

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

We got the idea for `ShortClassnames` by reading the "Tailoring Tinker with custom config" section of [Caleb Porzio](https://twitter.com/calebporzio)'s excellent blogpost "[Supercharge Your Laravel Tinker Workflow](https://blog.tighten.co/supercharge-your-laravel-tinker-workflow)".

## License

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

================================================
FILE: composer.json
================================================
{
    "name": "spatie/laravel-tinker-tools",
    "description": "Use short class names in an Artisan tinker session",
    "keywords": [
        "spatie",
        "laravel-tinker-tools",
        "flysystem",
        "dropbox",
        "v2",
        "api"
    ],
    "homepage": "https://github.com/spatie/laravel-tinker-tools",
    "license": "MIT",
    "authors": [
        {
            "name": "Freek Van der Herten",
            "email": "freek@spatie.be",
            "homepage": "https://spatie.be",
            "role": "Developer"
        }
    ],
    "require": {
        "php": "^7.0",
        "illuminate/support": "5.3.*|5.4.*"
    },
    "require-dev": {
        "phpunit/phpunit": "^6.0"
    },
    "autoload": {
        "psr-4": {
            "Spatie\\TinkerTools\\": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Spatie\\TinkerTools\\Test\\": "tests"
        }
    },
    "scripts": {
        "test": "vendor/bin/phpunit"
    },
    "config": {
        "sort-packages": true
    }
}


================================================
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="Spatie 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" charset="UTF-8" yui="true" highlight="true"/>
        <log type="coverage-text" target="build/coverage.txt"/>
        <log type="coverage-clover" target="build/logs/clover.xml"/>
    </logging>
</phpunit>


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

namespace Spatie\TinkerTools;

use ReflectionClass;

class ShortClassNames
{
    /** @var \Illuminate\Support\Collection */
    public $classes;

    public static function register(string $classMapPath = null)
    {
        $classMapPath = $classMapPath ?? base_path('vendor/composer/autoload_classmap.php');

        (new static($classMapPath))->registerAutoloader();
    }

    public function __construct(string $classMapPath)
    {
        $classFiles = include $classMapPath;

        $this->classes = collect($classFiles)
            ->map(function (string $path, string $fqcn) {
                $name = last(explode('\\', $fqcn));

                return compact('fqcn', 'name');
            })
            ->filter()
            ->values();
    }

    public function registerAutoloader()
    {
        spl_autoload_register([$this, 'aliasClass']);
    }

    public function aliasClass($findClass)
    {
        $class = $this->classes->first(function ($class) use ($findClass) {
            if ($class['name'] !== $findClass) {
                return false;
            }

            return ! (new ReflectionClass($class['fqcn']))->isInterface();
        });

        if (! $class) {
            return;
        }

        class_alias($class['fqcn'], $class['name']);
    }
}


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

namespace Spatie\TinkerTools\Test;

class NamespacedClass
{
    public static function getGreeting(): string
    {
        return 'Oh, hi Mark';
    }
}


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

namespace Spatie\TinkerTools\Test;

use Error;
use PHPUnit\Framework\TestCase;
use Spatie\TinkerTools\ShortClassNames;

class ShortClassNamesTest extends TestCase
{
    /** @test */
    public function it_can_register_short_name_classes()
    {
        $foundClass = false;

        try {
            \NamespacedClass::getGreeting();

            $foundClass = true;
        } catch (Error $error) {
        }

        $this->assertFalse($foundClass);

        ShortClassNames::register(__DIR__.'/../vendor/composer/autoload_classmap.php');

        $this->assertEquals('Oh, hi Mark', \NamespacedClass::getGreeting());
    }
}
Download .txt
gitextract_krs3r2ca/

├── .editorconfig
├── .gitattributes
├── .gitignore
├── .scrutinizer.yml
├── .styleci.yml
├── .travis.yml
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│   └── ShortClassNames.php
└── tests/
    ├── NamespacedClass.php
    └── ShortClassNamesTest.php
Download .txt
SYMBOL INDEX (9 symbols across 3 files)

FILE: src/ShortClassNames.php
  class ShortClassNames (line 7) | class ShortClassNames
    method register (line 12) | public static function register(string $classMapPath = null)
    method __construct (line 19) | public function __construct(string $classMapPath)
    method registerAutoloader (line 33) | public function registerAutoloader()
    method aliasClass (line 38) | public function aliasClass($findClass)

FILE: tests/NamespacedClass.php
  class NamespacedClass (line 5) | class NamespacedClass
    method getGreeting (line 7) | public static function getGreeting(): string

FILE: tests/ShortClassNamesTest.php
  class ShortClassNamesTest (line 9) | class ShortClassNamesTest extends TestCase
    method it_can_register_short_name_classes (line 12) | public function it_can_register_short_name_classes()
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (15K 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": 32,
    "preview": "build\ncomposer.lock\ndocs\nvendor\n"
  },
  {
    "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": 81,
    "preview": "preset: laravel\n\nlinting: true\n\ndisabled:\n  - single_class_element_per_statement\n"
  },
  {
    "path": ".travis.yml",
    "chars": 472,
    "preview": "language: php\n\nphp:\n  - 7.0\n  - 7.1\n  - 7.2\n\nenv:\n  matrix:\n    - COMPOSER_FLAGS=\"--prefer-lowest\"\n    - COMPOSER_FLAGS="
  },
  {
    "path": "CHANGELOG.md",
    "chars": 185,
    "preview": "# Changelog\n\nAll notable changes to `laravel-tinker-tools` will be documented in this file\n\n## 1.0.1 - 2017-07-28\n\n- avo"
  },
  {
    "path": "LICENSE.md",
    "chars": 1090,
    "preview": "The MIT License (MIT)\n\nCopyright (c) Spatie bvba <info@spatie.be>\n\nPermission is hereby granted, free of charge, to any "
  },
  {
    "path": "README.md",
    "chars": 6548,
    "preview": "**The functionality of this package is built into Laravel 5.5 and above, only install this in older Laravel versions**\n\n"
  },
  {
    "path": "composer.json",
    "chars": 1028,
    "preview": "{\n    \"name\": \"spatie/laravel-tinker-tools\",\n    \"description\": \"Use short class names in an Artisan tinker session\",\n  "
  },
  {
    "path": "phpunit.xml.dist",
    "chars": 1046,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit bootstrap=\"vendor/autoload.php\"\n         backupGlobals=\"false\"\n         "
  },
  {
    "path": "src/ShortClassNames.php",
    "chars": 1295,
    "preview": "<?php\n\nnamespace Spatie\\TinkerTools;\n\nuse ReflectionClass;\n\nclass ShortClassNames\n{\n    /** @var \\Illuminate\\Support\\Col"
  },
  {
    "path": "tests/NamespacedClass.php",
    "chars": 160,
    "preview": "<?php\n\nnamespace Spatie\\TinkerTools\\Test;\n\nclass NamespacedClass\n{\n    public static function getGreeting(): string\n    "
  },
  {
    "path": "tests/ShortClassNamesTest.php",
    "chars": 634,
    "preview": "<?php\n\nnamespace Spatie\\TinkerTools\\Test;\n\nuse Error;\nuse PHPUnit\\Framework\\TestCase;\nuse Spatie\\TinkerTools\\ShortClassN"
  }
]

About this extraction

This page contains the full source code of the spatie/laravel-tinker-tools GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (13.5 KB), approximately 3.7k tokens, and a symbol index with 9 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!