Giter Site home page Giter Site logo

kristofmorva / laravel-ide-macros Goto Github PK

View Code? Open in Web Editor NEW
45.0 2.0 28.0 36 KB

Generating a helper file for IDEs to support Laravel's macros, as a supplementary to barryvdh's Laravel Ide Helper.

License: MIT License

PHP 100.00%
laravel ide-helper macros

laravel-ide-macros's Introduction

Warning

This repository is archived because I'm unable to maintain it, as I'm not a web developer anymore and forgot most of this stuff.

Please use an existing fork, or create your own with your changes.

Sorry about this, have fun working on whatever you're currently building :)

Laravel IDE Macros

It is advised to be used with Laravel IDE Helper, which generates helper files for your IDE, so it'll be able to highlight and understand some Laravel-specific syntax. This package provides an additional IDE helper file for Laravel macros with the syntax you are already used to in Laravel IDE Helper.

Installation

Just require it in your Composer file, and you are good to go:

"tutorigo/laravel-ide-macros": "*"

If you are using Laravel 5.4 or lower, you must register the IdeMacrosServiceProvider manually.

Configuration

Run the following command to publish the configuration file to config/ide-macros.php:

php artisan vendor:publish --provider="Tutorigo\LaravelMacroHelper\IdeMacrosServiceProvider"

Usage

Generate helper file

Run the following command to generate the macro IDE helpers:

php artisan ide-helper:macros

Use of non-static macros

Macros can be both static (ie. Route::sth()) and non-static (ie. Request::route()->sth()). To distinct the two, use the @instantiated tag in the PHPDoc of macros, which depend on $this, for example:

/**
 * Gets the amount of route parameters
 *
 * @return array
 * @instantiated
 */
\Illuminate\Routing\Route::macro('parameterCount', function () {
    /** @var \Illuminate\Routing\Route $this */
    return count($this->parameters);
});

laravel-ide-macros's People

Contributors

almas1992 avatar banqhsia avatar cupoftea696 avatar inxilpro avatar kristofmorva avatar kylekatarnls avatar laravel-shift avatar mhkb avatar mortenscheel avatar nuernbergera avatar robertboes avatar sixmonkey avatar teakowa avatar vaites 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

Watchers

 avatar  avatar

laravel-ide-macros's Issues

ErrorException : Function ReflectionType::__toString() is deprecated

class ReflectionType
{
	/**
	 * To string
	 * @link https://php.net/manual/en/reflectiontype.tostring.php
	 * @return string Returns the type of the parameter.
	 * @since 7.0
	 * @deprecated 7.1 Please use getName()
	 * @see \ReflectionType::getName()
	 */
	public function __toString()
	{
	}
}

Adding getName() after getType() on line 178 of MacrosCommand seems to fix the problem.

$this->write($parameter->getType()->getName() . " ");

Error when running on project with invokable macros

I came across this issue when using laravel nova in my project, the generation would fail due to this package not properly handling an invokable class macro definition.

Symfony\Component\Debug\Exception\FatalThrowableError  : ReflectionFunction::__construct() expects parameter 1 to be string, object given

  at /Users/jack/SparkSquared/SparklesAPI/vendor/tutorigo/laravel-ide-macros/src/Console/MacrosCommand.php:96
     92|                         if (is_array($macro)) {
     93|                             list($class, $method) = $macro;
     94|                             $function = new \ReflectionMethod(is_object($class) ? get_class($class) : $class, $method);
     95|                         } else {
  >  96|                             $function = new \ReflectionFunction($macro);
     97|                         }
     98| 
     99|                         if ($comment = $function->getDocComment()) {
    100|                             $this->writeLine($comment, $this->indent);

  Exception trace:

  1   ReflectionFunction::__construct(Object(Laravel\Nova\Macros\FirstDayOfQuarter))
      /Users/jack/SparkSquared/SparklesAPI/vendor/tutorigo/laravel-ide-macros/src/Console/MacrosCommand.php:96

My current solution to the issue is the following:

                        if (is_array($macro)) {
                            list($class, $method) = $macro;
                            $function = new \ReflectionMethod(is_object($class) ? get_class($class) : $class, $method);
                        } else {
                            if (is_object($macro)) {
                                $function = (new \ReflectionObject($macro))->getMethod('__invoke');
                            } else {
                                $function = new \ReflectionFunction($macro);
                            }
                        }

Problem with MacrosCommand.php::generateFunction

Hello here,

This is an example of a macro :

use Carbon\Carbon;

Carbon::macro('example', function (Carbon $otherDate) {
   // ... some any code
});

When I generate macro via

php artisan ide-helper:macros

the generated _ide_macros.php contains something like that :

namespace Carbon {
   class Carbon {
        public static function example(Carbon\Carbon $otherDate) {

        }
   }
}

And we can see the type of $otherDate is wrong. I think that the easiest is to add the prefix \ in all types.

Thanks for your work :)

Call to undefined method ReflectionUnionType::getName() when trying to install

When i run composer require tutorigo/laravel-ide-macros i get this error after package discovery:

> Illuminate\Foundation\ComposerScripts::postUpdate
> @php artisan ide-helper:generate

   Error

  Call to undefined method ReflectionUnionType::getName()

  at C:\project\vendor\barryvdh\laravel-ide-helper\src\Macro.php:45
     41▕
     42▕         // Add macro parameters if they are missed in original docblock
     43▕         if (!$this->phpdoc->hasTag('param')) {
     44▕             foreach ($method->getParameters() as $parameter) {
  ➜  45▕                 $type = $parameter->hasType() ? $parameter->getType()->getName() : 'mixed';
     46▕                 $type .= $parameter->hasType() && $parameter->getType()->allowsNull() ? '|null' : '';
     47▕
     48▕                 $name = $parameter->isVariadic() ? '...' : '';
     49▕                 $name .= '$' . $parameter->getName();

  1   C:\project\vendor\barryvdh\laravel-ide-helper\src\Method.php:64
      Barryvdh\LaravelIdeHelper\Macro::initPhpDoc()

  2   C:\project\vendor\barryvdh\laravel-ide-helper\src\Macro.php:30
      Barryvdh\LaravelIdeHelper\Method::__construct()
Script @php artisan ide-helper:generate handling the post-update-cmd event returned with error code 1

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

It's a pretty recent (February) Laravel 8 project with PHP 8.

Macros with both @static and @instanciated

Hello,

Most macros are callable both statically and dynamically.

A simple example:

<?php

Carbon::macro('getHexadecimalYear', function () {
  return dechex((isset($this) ? $this : static::now())->year);
});

echo Carbon::parse('1998-06-17')->getHexadecimalYear();
echo "\n";
echo Carbon::getHexadecimalYear();

getHexadecimalYear works well statically (use current date) and on instance (use the instance year).

And in practice, you can't prevent any macro to be called in a way or the other unless you throw an exception from inside the macro.

So I think the right approach is to create 2 files _ide_static_macros.php and _ide_dynamic_macros.php and put every macro with and without static keyword until an explicit annotation such as @static / @instanciated would be present in the PHPDoc, in this case only the macro would be in only one file.

What do you think of it?

Fix generating helper for `...` token.

Incorrect code gets generated, when using ... token.

Example:

/**
 * @instantiated
 */
Browser::macro('assertSeeMultiple', function (string ...$searchKeys): Browser {
    foreach ($searchKeys as $key) {
        /** @var Browser $this */
        $this->assertSee($key);
    }

    return $this;
});

will generate

/**
 * @instantiated
 */
public function assertSeeMultiple(...string $searchKeys): \Laravel\Dusk\Browser { //should be `string ...$searchKeys`

}

Return typehits of primitive values

It looks like the return typehints that are primitive values (bool, array, string, etc.) are being handled like they need a namespace. For example:

public static function validate($callback): \bool {

or

public static function pluckToArray($value, $key = NULL): \array {

This doesn't seem to matter for bool. However, if the return is array, prefixing it with a backslash causes the interpreter to freak out and nothing after that line is interpreted by the IDE. The error messages my IDE throw are: "Method should either have body or be abstract" and "Unexpected: array".

To reproduce, create a new Laravel app and install your package and Spatie's Collection Macros:

laravel new ide-macro-test && \
cd ide-macro-test && \
composer require spatie/laravel-collection-macros tutorigo/laravel-ide-macros && \
php artisan ide-helper:macros

Check line 72 of _ide_macros.php.

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.