Giter VIP home page Giter VIP logo

drupal-code-generator's Introduction

Drupal Code Generator

Tests Total Downloads Minimum PHP Version

A command line code generator for Drupal.

Installation

composer require chi-teck/drupal-code-generator --dev

Optionally, generate shell completions for DCG executable.

./vendor/bin/dcg completion bash >> ~/.bash_completion

Usage

# Display navigation.
./vendor/bin/dcg

# Call generator directly.
./vendor/bin/dcg plugin:field:widget

# Generate code non-interactively.
./vendor/bin/dcg config-form -a Example -a example -a SettingsForm -a No

Compatibility

DCG PHP Symfony Twig Drupal Drush
1 7.1 - 7.4 3, 4 1, 2 7, 8 9, 10
2 7.4+ 4, 5 2, 3 7, 9 11
3 8.1+ 6 3 10 12
4 8.3+ 7 3 11 13

License

GNU General Public License, version 2 or later.

drupal-code-generator's People

Contributors

alexpott avatar andypost avatar chesn0k avatar chi-teck avatar dependabot-preview[bot] avatar dependabot[bot] avatar el7cosmos avatar larowlan avatar mfb avatar niklan avatar petersricardo avatar petk avatar pfrenssen avatar pierrepaul avatar rpayanm avatar sanduhrs avatar stefan-korn avatar webflo avatar weitzman 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

drupal-code-generator's Issues

Entity: The class prefix is based on the entity type label

Right now, if you generate a new content entity, the class prefix is based on the camel-ization of the entity label. That means that if you have some special characters in your entity label, even if you fix it manually in the entity type id prompt, the class names will still be based on the label.

For example, if you create a module providing an content entity type with label "Føo Bår" and entity type id "foo_bar", instead of getting src/Entity/FooBar.php, you'll get src/Entity/FOBR.php

Database prefixes in PHPSTORM_META

PhpStorm 2021.1 will support Database prefixes. Should we add support for it?

namespace PHPSTORM_META {
  override(
    // Virtual function to indicate that all SQL
    // injections will have the following replacement rules.
    sql_injection_subst(),
    map([
      '{' => "PS2021_", // all `{` in injected SQL strings will be replaced with a prefix
      '}' => '',        // all `}` will be replaced with an empty string
    ]));
}

I can try to implement it.

Missing info.yml while generating a content entity

While generating a content entity and creating a new module in the process there won't be a generated *.info.yml
It seems to me this is because the command is extending the src/Command/ModuleGenerator.php Class, and the yml is created by the src/Command/Module.php class.

Add Revision UI while generating a content entity

As per the Issue #2350939 on Drupal.org we can have Revision UI for Revisionable Entities.

Update Content Entity Generator class to include Revision UI annotations in Entity Class .

The CR has additional details for the syntaxes

Edit:

We might need to consider the changes that might be introduced in the issue #2976861 as well. Thanks.

The class_alias in bootstrap.php causes warnings when using preloading

I am using a generated preloading script which looks something like this:

$loader = require_once '/app/web/autoload.php';
// more lines to load PSR-4 directories (irrelevant to this issue)

$files = [
    '/app/vendor/autoload.php',
    '/app/load.environment.php',
    '/app/vendor/composer/autoload_static.php',
    // more files to be preloaded
];

foreach ($files as $file) {
    try {
        if (!(is_file($file) && is_readable($file))) {
            throw new \Exception("{$file} does not exist or is unreadable.");
        }
        require_once $file;
    } catch (\Throwable $e) {
        // ...
        throw $e;
    }
}

This script is set to opcache.preload setting. The script works and I see that the preload is making a difference, but there is a warning on all pages.


Warning: Cannot declare class DrupalCodeGenerator\Twig\TwigEnvironment, because the name is already in use in /app/vendor/chi-teck/drupal-code-generator/src/bootstrap.php on line 44

Warning: Cannot declare class DrupalCodeGenerator\TwigEnvironment, because the name is already in use in /app/vendor/chi-teck/drupal-code-generator/src/bootstrap.php on line 47

After debugging, I realized this is because bootstrap.php is loaded by composer (it's part of composer.json's autoload.files option). As the warnings suggest, this is due to the class_alias line.

After a lot of debugging and research, I conclude that the problem is that the preloading works somewhat differently for class_alias. In other words, this could be a PHP bug and I do some hints for this in php/php-src#3538 and symfony/symfony#29105.

My theory is that while preloading correctly handles all the regular classes and functions, it cannot handle class_alias properly. Since class_alias runs both while preloading (as we are requiring the autoloader) and during the execution, it seems that the internal PHP entry for the class name persists during the runtime causing the warning.

The fix in my case was to wrap the class_alias call inside an if block with class_exists condition. I don't see any warnings after that. I'm going to create a PR against 1.x branch for that shortly.

Footnote: This is tangentially related to #46 but I don't know if this change would help static analyzers.

Do not override constructors for service objects, plugins, and controllers

Problem/Motivation

According to the Drupal 8 Backward Compatibility Policy, constructors for service objects are considered internal, which means they are subject to change on a minor release:

The constructor for a service object (one in the container), plugin, or controller is considered internal unless otherwise marked, and may change in a minor release. These are objects where developers are not expected to call the constructor directly in the first place. Constructors for value objects where a developer will be calling the constructor directly are excluded from this statement.

The implication is that if we override their constructors, and they happen to change their signature on a minor release, it would require us to update our current code for all instances where we're overriding their constructors, to conform to the new signature. This shouldn't have to happen to conform to a minor release.

There is a good blog post from jrockwitz (maintainer of Webform for D8), that goes into more detail: https://www.jrockowitz.com/blog/webform-road-to-drupal-9

Solution

We can implement a new design pattern that would fix the problem.

As an example, from the controller command, injecting 3 services as an example.

Before:

...
  public function __construct(
    RequestStack $request_stack,
    LoggerInterface $logger,
    Client $httpClient) {
    $this->request = $request_stack->getCurrentRequest();
    $this->logger = $logger;
    $this->httpClient = $httpClient;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack'),
      $container->get('logger.factory')->get('foo'),
      $container->get('http_client')
    );
  }
...

After:

...
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->request = $container->get('request_stack')->getCurrentRequest();
    $instance->logger = $container->get('logger.factory')->get('foo');
    $instance->httpClient = $container->get('http_client');
    return $instance;
  }
...

Some of the most used Drupal contrib modules are already using this design pattern, like the aforementioned Webform, Migrate Plus, Search API, etc.

Some extra benefits from this approach also include less code bloat:

  • We no longer need a __construct() method, since the __construct() and create() methods are effectively merged into one.
  • We no longer need a use statement per service injected. Their only purpose was so we could typehint on the constructor.

That reduces the final code lines by quite a bit. Also due to the above, adding a new service dependency injection after already running the generate command is no longer a major PITA.

I think this solution would include:

  • A change in di.twig's container(services) macro that would use this new design pattern.
  • A change to the generator twig template files, to use this new function, and also remove the now unnecessary use statements as well as the constructor.

I have a PR ready for these changes.

This solution could be applied to the following generators:

  • controller
  • block
  • views-argument-default
  • views-field

Improve Action Plugin generation

Problem

Current Action Generator can only generate Plugin and scheme, but Action Plugins can also define config/install/system.action.{ACTION_ID}.yml file for other purposes (reference). I don't know exactly all the places where it uses, but at least for Views Bulk Operations.

Solution

My suggestion is to improve the generator, by letting user to decide, whether need it or not (generate config entity for action).

At least, I think, this must be noticed in @DCG comment as it done for FieldUpdateActionBase.

Rationale of this project?

I'm kind of confused, because I thought, that generating boilerplate code is a Drupal Console task now. Why should I use this project, instead of DC? Is there some sort of feature comparison anywhere?

Minor issue with `drush generate service:custom`

Describe the bug
A new custom service is placed in the parameters section of an existing module_name.services.yml file if the parameters section is placed after the services section.

To Reproduce

  1. Create a custom service using drush generate service:custom
  2. Manually add a parameters section the new module_name.services.yml below the services section.
  3. Create a second custom service using drush generate service:custom

Expected behavior
The second service should be added to the services section of module_name.services.yml

Actual behavior
The second service is added to the parameters section of module_name.services.yml

Workaround
Either:

  1. Be sure to manually add the parameters section above the services section of module_name.services.yml
  2. Manually move the definition of the second service created to the services section.

Note: I originally filed this issue here: drush-ops/drush#5267

1.x: Ensure that the default answer is normalized

When the answer option is specified and running in non-interactive mode, the default answer retrieved in the InputHandler

Sometimes needs to be normalized like this: https://github.com/symfony/console/blob/cbb6922/Helper/QuestionHelper.php#L146-L148

Using the update_helper module and running the following:

drush generate configuration-update --answers='{"module":"my_module"}'

Where the include-modules option is omitted so that the default value is used and normalized from a string to an array, however, that doesn't appear to be the case.
So it leads to a crash because the value is a string rather than an array.

Perhaps it should have an additional check for if it's a string before attempting to normalize to avoid accidentally normalizing an already normalized default answer:

if ($normalizer = $question->getNormalizer()) {
  if (is_string($answer)) {
    // Normalize from string to the appropriate format.
    $answer = $normalizer($answer);
  }
}

Class name validator

Hi,
is there any reason why in validateClassName method you require on the second place only 0 from numbers? Referenced doc says nothing about that.

Bundle generation

Hey. Thanks for this code, I am using it through Drush 9. I am migrating a site from D7 to D8 that uses the Entity Construction Kit (ECK). I'd love to not have to use ECK in D8. Given the progress in code generation with D8, like Drupal Console and your project, I think it might be feasible to get rid of it.

I was wondering if there is a way, or a plan, to be able to generate different bundles with the Content Entity generator? Using Drush I generated a fieldable entity, which is awesome, but I am going to need a chunk of bundles within that entity.

how to use default values via --answers options

When providing answers via the --answers option, is it possible to allow the default values to be used non-interactively?

For example, dcg twig-extension -a '{"name": "Example", "machine_name": "example", "class": "ExampleTwigExtension"}' Leaving off class prompts for input. Other values like true, false and null don't seem to work either.

Thanks!

Add `All`option to entity:bundle-class

On www.mass.gov we have 35 node types (see below). I really dont want to type 1-35 separated by commas, nor do I want to run this command many many times. How about an All option at the top of the list?

Bundles, comma separated:
  [ 1] Right-rail (prototype)
  [ 2] Advisory
  [ 3] Alert (Page-level and Organization)
  [ 4] Binder
  [ 5] Promotional page
  [ 6] Contact Information
  [ 7] Curated List
  [ 8] Decision
  [ 9] Decision Tree
  [10] Decision Tree Branch
  [11] Decision Tree Conclusion
  [12] Error
  [13] Event
  [14] Executive Order
  [15] External data resource
  [16] Fee
  [17] Form
  [18] Guide
  [19] How-to
  [20] Information Details
  [21] Interstitial
  [22] Location
  [23] Location Detail
  [24] News
  [25] Organization
  [26] Basic page (prototype)
  [27] Person
  [28] Regulation
  [29] Rules of Court
  [30] Service Details
  [31] Service
  [32] Alert (Sitewide)
  [33] Stacked layout (prototype)
  [34] Topic Page
  [35] Utility Drawer

Also, we forgot to make an alias for entity:bundle-class. The command listing looks inconsistent without it.

Generating a content entity with revisions does not provide UI

Is your feature request related to a problem? Please describe.
When I generate a content entity with revisions (in our case drush generate module-content-entity), the UI for managing revisions is not created.

Describe the solution you'd like
When I generate a content entity with revisions, the ui for managing revisions is created. We should handle creating the revisions UI like other revisionable core content entities (Node). We will need to create the Controller, Forms, Permissions, Route definitions and Local Tasks.

Here are some example required assets:

Alternatively, when core provides a generic revision ui, we could implement that as well.

Describe alternatives you've considered
It is possible to create the UI by hand, but is pretty laborious.

Additional context
Translation may add some additional complexity here. It seems like Node's revision controller is pretty language reliant.

Does it mistake or works as designed?

It's a bit confusing: https://github.com/Chi-teck/drupal-code-generator/blob/master/templates/d8/module/content-entity/src/Entity/Example.php.twig#L148-L158

  /**
   * {@inheritdoc}
   */
  public function isEnabled() {
    return (bool) $this->get('status')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setStatus($status) {
    $this->set('promote', $status);
    return $this;
}

Why is setStatus() change promote field? Does it correct? Because isEnabled() get status from status field. Maybe it's better to rename setStatus() to setPromote() in that way?

Add contributing instructions

Hi, thanks for your code generator project. I just found out that this is what drives drush generate in Drush 9.

Maybe it would be good to add some documentation or instructions to your README, explaining how people can contribute to the project. For instance, if I know a plugin type that is not yet covered by the code generator, what should I do to help add it?

Thank you!

Replace or improve Drupal versions mentions

Since there is already Drupal 9, some things can be confusing.

I suggest replacing mentioning "Drupal 8" with "Drupal" or "Drupal 8+", depends on preference and context.

The project has 17 occurrences for "Drupal 8" for now:

image

For example /templates/module-file/module.twig has comment "This file is no longer required in Drupal 8.". This can be improved like so "This file is no longer required in Drupal 8+.", "This file is no longer required in Drupal." or "This file is no longer required since Drupal 8.". Since there is the link for the change record explains this, I don't think version is needs to be mentioned.

For reference, we can use Drupal Core convention — Drupal is mentioned without major version.

I want to discuss this before doing any changes.

Drop support for global installation

That applies to both Composer and PHAR installation.

Reasons

  1. It seems global installation is not widely used. Most people have DCG installed as a local Composer package and use it through Drush.

  2. Maintenance cost. No need to dump services and hooks for autocompletion. Also PHAR compiler can be removed.

  3. Reducing complexity. Currently generators follow "Progressive Enhancement" strategy. Meaning they are capable to work when Drupal is not bootstrapped. And if Drupal context is availble they can enhance user experience somehow. For instance by providing more accurate autocompletion. In practice that looks like follows.

    if ($this->drupalContext) {
      // Some code that enhances UX if Drupal is installed.
    }

    This duality brings complexity. With this change we can get rid of this condition and assume that Drupal Context is always available. Eventually that would allow generators to implement deeper integration with Drupal.

Proposed solution

  • Update installation instruction in README.md and stop generating PHAR file since 2.4.0.
  • Remove Drupal Conext conditions, dumper scripts, PHAR complier, etc.
  • Require Drupal core for testing.

Remove asset-packagist as a repo source

Asset Packagist has failed to renew its domain, with a "Renew" link that points to a Russian registrar.

There are well documented workarounds to help projects move away from asset-packagist, eg
https://ryanszrama.com/blog/04-18-2022/replace-asset-packagist-custom-package-repositories

For more details, see thread on Drupal community slack's #contribute channel: https://drupal.slack.com/archives/C1BMUQ9U6/p1650304302016749

Suggested approach, remove mention of asset packagist from codebase.

I found these mentions in code:

src/Command/Drupal_8/Project.php:108:    $questions['asset_packagist'] = new ConfirmationQuestion('Would you like to add asset-packagist repository?', FALSE);
src/Command/Drupal_8/Project.php:217:        'url' => 'https://asset-packagist.org',

Rethink the namespace for Entity Bundle Classes

For now, entity bundle classes generated by DCG 2 are placed in the namespace Drupal\mymodule\Entity\Bundle:

<?php

namespace Drupal\mymodule\Entity\Bundle;

use Drupal\node\Entity\Node;

/**
 * A bundle class for node entities.
 */
class ArticleBundle extends Node {
...
}

However, most documentation and blog posts I've seen for now favor putting them directly in the 'Entity' namespace. Here's an excellent example: https://www.hashbangcode.com/article/drupal-9-entity-bundle-classes.

This is highly opinionated, but IMHO DCG should follow established best practices, so I'd suggest changing the namespace.

Add ability to generate themes at destination modules/custom

I'm trying to write a generator like this

class SubthemeGenerator extends BaseGenerator
{
    protected $name = 'd8:theme-mytheme';
    protected $description = 'Generates a subtheme.';
    protected $alias = 'mytheme';
    protected $templatePath = __DIR__;
    protected $destination = 'themes/custom';

}

But seems like $destination is ignored and it generates the subtheme at the Drupal root.

Is it possible to define a custom destination path relative to the drupal root?

Entity administer permissions

Currently, content entity generates this kind of permissions:

Example:

…
{% if bundle %}
 *   admin_permission = "administer {{ entity_type_label|lower }} types",
{% elseif fieldable %}
 *   admin_permission = "administer {{ entity_type_label|lower }}",
{% else %}
…

Is that safe and works as intended or this is a bug?

If user tries to generate custom entity and gives it label "Node" it will share permissions with core "node" module. This is not very obvious and can lead to a lot of problems in the future.

Config entity type on the other hand, uses entity_type_id.

I propose to change content entity type permission from using this {{ entity_type_label|lower }} to that {{ entity_type_label }}. This will make generation across entity types consistent and safer for common entity labels.

Latest tag missing from packagist

Tag 1.28.1 is missing from packagist.org :
https://github.com/Chi-teck/drupal-code-generator/releases/tag/1.28.1
https://packagist.org/packages/chi-teck/drupal-code-generator

And since drush 9.6.1 :
drush-ops/drush@6f30e99

When running composer up drush/drush --with-all-dependencies we are cloning dev-master version.

Gathering patches for root package.
Loading composer repositories with package information
[...]

  • Removing chi-teck/drupal-code-generator (1.28.0)
  • Installing chi-teck/drupal-code-generator (dev-master 2e093f5): Cloning 2e093f5 from cache
  • Updating drush/drush (9.6.0 => 9.6.1): Downloading (100%)

composer show chi-teck/drupal-code-generator --all|grep versions

versions : dev-master, 1.x-dev, * 1.28.0, 1.27.0, 1.26.3, 1.26.2, 1.26.1, 1.26.0, 1.25.1, 1.25.0, 1.24.0, 1.23.2, 1.23.1, 1.23.0, 1.22.0, 1.21.3, 1.21.2, 1.21.1, 1.21.0, 1.20.0, 1.19.0, 1.18.4, 1.18.3, 1.18.2, 1.18.1, 1.18.0, 1.17.5, 1.17.4, 1.17.3, 1.17.2, 1.17.1, 1.17.0, 1.16.0, 1.15.1, 1.15.0, 1.14.0, 1.13.0, 1.12.1, 1.12.0, 1.11.0, 1.10.2, 1.10.1, 1.10.0, 1.9.1, 1.9.0, 1.8.1, 1.8.0, 1.7.0, 1.6.1, 1.6.0, 1.5.0, 1.4.1, 1.4.0, 1.3.0, 1.2.1, 1.2.0, 1.1.0, 1.0.3, 1.0.2, 1.0.1, 1.0.0

Version check causes Twig Environment class to be loaded early

The test for the Twig version in bootstrap.php is loading the Environment class early, even when just parsing for code analysis. I'm just starting to look at this, and I think I'm right the test doesn't happen early in the v2 (master) branch, only v1 used by Drush? So am wondering if there is already a good alternative?

I stumbled onto the issue because of phpactor/phpactor#1043

can't cd to /var/www/dcg: No such file or directory

While working on #59, I run ./scripts/run-sut-tests.sh

This script makes the assumption of where DCG is located.

So, my run ends up with error:

./scripts/run-sut-tests.sh: cd: line 10: can't cd to /var/www/dcg: No such file or directory

Looks like it's called at the very end, so this is not a big deal. But why it's even called? Looks like it doesn't do anything and removing this line doesn't change anything.

core: 8.x in model.info.yml

Hi there,

in the model.info.yml (templates/module/model.info.yml.twig) used for generating a module info yml, there is still a reference to core: 8.x
I think with D8 being end of live removing this line would be enough and it doesn't need to be configurable.
Do you agree?
If you want it to be configurable, I could set up a pull request.

Why don't I get a menu link for my settings page when I generate a module?

I was thinking about adding a template to generate the links menu, but I found that links.menu.twig already exists. Still, the file is not generated. Is this a known issue?

Did not dig into the code.

$ drush generate module

 Welcome to module-standard generator!
–––––––––––––––––––––––––––––––––––––––

 Module name:
 ➤ Guest Upload

 Module machine name [guest_upload]:
 ➤ 

 Module description [The description.]:
 ➤ Allow anonymous users to upload images

 Package [Custom]:
 ➤ Other

 Dependencies (comma separated):
 ➤ block_upload

 Would you like to create install file? [Yes]:
 ➤ 

 Would you like to create libraries.yml file? [Yes]:
 ➤ no

 Would you like to create permissions.yml file? [Yes]:
 ➤ 

 Would you like to create event subscriber? [Yes]:
 ➤ 

 Would you like to create block plugin? [Yes]:
 ➤ no

 Would you like to create a controller? [Yes]:
 ➤ 

 Would you like to create settings form? [Yes]:
 ➤ 

 The following directories and files have been created or updated:
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
 • modules/custom/guest_upload/guest_upload.info.yml
 • modules/custom/guest_upload/guest_upload.install
 • modules/custom/guest_upload/guest_upload.module
 • modules/custom/guest_upload/guest_upload.permissions.yml
 • modules/custom/guest_upload/guest_upload.routing.yml
 • modules/custom/guest_upload/guest_upload.services.yml
 • modules/custom/guest_upload/src/Controller/GuestUploadController.php
 • modules/custom/guest_upload/src/EventSubscriber/GuestUploadSubscriber.php
 • modules/custom/guest_upload/src/Form/SettingsForm.php

Feature request: Plugin generator for content entity type

Right now, DCG can only generate modules for a content entity. But existing modules might want to add a new content entity type. Is it possible to create a template for that? Where would I copy/move the existing files from the module version? Maybe I can send a PR.

(The idea is for this to make it into Drush, which I believe uses this project anyway.)

Drupal 10, Drush 11 compatibility with Drupal Code Generator

Drush 11.5.1 still requires chi-teck/drupal-code-generator ^2.4

But when I try to use drush generate, it is broken.

I tried to require chi-teck/drupal-code-generator ^3, but it conflicts with drush requirements.

Is there any suggested path that works right now for Drupal 10 with Drush 11?

❯ ddev drush generate theme
 [warning] Undefined variable $container ApplicationFactory.php:74
TypeError: DrupalCodeGenerator\Helper\DrupalContext::__construct(): Argument #1 ($container) must be of type Symfony\Component\DependencyInjection\ContainerInterface, null given, called in /var/www/html/vendor/drush/drush/src/Commands/generate/ApplicationFactory.php on line 74 in /var/www/html/vendor/chi-teck/drupal-code-generator/src/Helper/DrupalContext.php on line 43 #0 /var/www/html/vendor/drush/drush/src/Commands/generate/ApplicationFactory.php(74): DrupalCodeGenerator\Helper\DrupalContext->__construct(NULL)
#1 /var/www/html/vendor/drush/drush/src/Commands/generate/GenerateCommands.php(52): Drush\Commands\generate\ApplicationFactory->create()
#2 [internal function]: Drush\Commands\generate\GenerateCommands->generate('theme', Array)
#3 /var/www/html/vendor/consolidation/annotated-command/src/CommandProcessor.php(257): call_user_func_array(Array, Array)
#4 /var/www/html/vendor/consolidation/annotated-command/src/CommandProcessor.php(212): Consolidation\AnnotatedCommand\CommandProcessor->runCommandCallback(Array, Object(Consolidation\AnnotatedCommand\CommandData))
#5 /var/www/html/vendor/consolidation/annotated-command/src/CommandProcessor.php(176): Consolidation\AnnotatedCommand\CommandProcessor->validateRunAndAlter(Array, Array, Object(Consolidation\AnnotatedCommand\CommandData))
#6 /var/www/html/vendor/consolidation/annotated-command/src/AnnotatedCommand.php(390): Consolidation\AnnotatedCommand\CommandProcessor->process(Object(Symfony\Component\Console\Output\ConsoleOutput), Array, Array, Object(Consolidation\AnnotatedCommand\CommandData))
#7 /var/www/html/vendor/symfony/console/Command/Command.php(312): Consolidation\AnnotatedCommand\AnnotatedCommand->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#8 /var/www/html/vendor/symfony/console/Application.php(1040): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#9 /var/www/html/vendor/symfony/console/Application.php(314): Symfony\Component\Console\Application->doRunCommand(Object(Consolidation\AnnotatedCommand\AnnotatedCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#10 /var/www/html/vendor/symfony/console/Application.php(168): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#11 /var/www/html/vendor/drush/drush/src/Runtime/Runtime.php(124): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#12 /var/www/html/vendor/drush/drush/src/Runtime/Runtime.php(51): Drush\Runtime\Runtime->doRun(Array, Object(Symfony\Component\Console\Output\ConsoleOutput))
#13 /var/www/html/vendor/drush/drush/drush.php(77): Drush\Runtime\Runtime->run(Array)
#14 /var/www/html/vendor/drush/drush/drush(4): require('/var/www/html/v...')
#15 /var/www/html/vendor/bin/drush(120): include('/var/www/html/v...')
#16 {main}
TypeError: DrupalCodeGenerator\Helper\DrupalContext::__construct(): Argument #1 ($container) must be of type Symfony\Component\DependencyInjection\ContainerInterface, null given, called in /var/www/html/vendor/drush/drush/src/Commands/generate/ApplicationFactory.php on line 74 in DrupalCodeGenerator\Helper\DrupalContext->__construct() (line 43 of /var/www/html/vendor/chi-teck/drupal-code-generator/src/Helper/DrupalContext.php).
 [warning] Drush command terminated abnormally.
Failed to execute command drush generate theme: exit status 1```

[1.x] Running commands from other commands, `HelperSet` is initialised at Application level, so InputHandler is filled with questions from prior commands.

This affects running multiple commands from one

Running commands from other commands, HelperSet is initialised at Application level, so InputHandler is filled with questions from prior commands.

I have a generator that:

  • reads in csv data
  • calls another command to generate entity types with that data (repeatedly)

The input from the last command is still present because the InputHandler is not re-initialised each command only at application level.

Potential solutions:

  • Initialise a command initiated HelperSet instead of at Application
  • Re-initialise InputHandler within the command so it is clean when the command is run.

Happy to implement a solution, would either of the above solutions be preferred or accepted?

Template for d8 migrate source generates incorrect code

Observed in 1.32.1, but 1.32.5 still has this issue.

Template for d8 migrate source includes the following function:

  public function getIds() {
    $ids['id']['type'] = [
      'type' => 'integer',
      'unsigned' => TRUE,
      'size' => 'big',
    ];
    return $ids;
  }

This should be

  public function getIds() {
    $ids['id'] = [
      'type' => 'integer',
      'unsigned' => TRUE,
      'size' => 'big',
    ];
    return $ids;
  }

Building a source using with type/unsigned/size under the additional type key causes the error message

[error] Migration failed with source plugin exception: The "" plugin does not exist. Valid plugin IDs for Drupal\Core\Field\FieldTypePluginManager are: block_field, datetime, daterange, entity_reference_revisions, file_uri, file, image, link, metatag, list_float, list_string, list_integer, path, redirect_source, text_with_summary, text, text_long, video_embed_field, viewsreference, integer, uri, entity_reference, uuid, float, email, timestamp, string, language, created, changed, map, string_long, password, decimal, boolean

to be triggered on running migrate:import

PR to follow.

[3.x] Decide on coding standard for generated code

Drupal 10 will require PHP 8.1 which means we can make use of all new PHP features available at this moment. However, Drupal coding standards weren't updated yet to reflect this change and will unlikely be updated in the foreseeable future. Furthermore, they don't cover PHP 7 features yet.
So far, all code generated by DCG follows Drupal core coding standards. Which means if something is not covered in Drupal coding standards it uses Drupal core code base as a referencing point. Nowadays, the generated code looks very outdated as most of Drupal core code is written using PHP 5 syntax only.

For custom projects it's not a problem to establish own standards for features that are missing in the Drupal coding standards.
Example: https://github.com/Chi-teck/drupal-coder-extension

However, for generated code that is going to be part of other projects it needs sort of community approval.

Here is an example of the currently generated code.
https://github.com/Chi-teck/drupal-code-generator/blob/3.0.0-alpha2/tests/functional/Generator/_controller/src/Controller/FooController.php

The following example represents proposed updates.

<?php declare(strict_types = 1);

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for Example routes.
 */
final class ExampleController extends ControllerBase {

  /**
   * The controller constructor.
   */
  public function __construct(
    private readonly EntityTypeManagerInterface $entity_type_manager,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new self($container->get('entity_type.manager'));
  }

  /**
   * Builds the response.
   */
  public function build(): array {
    $build['content'] = [
      '#type' => 'item',
      '#markup' => $this->t('It works!'),
    ];
    return $build;
  }

}

Here is an overview of the changes:

  1. Declare strict types. #3250827
  2. Use final/private/self keywords to define non-abstract classes. #3019332
  3. Use constructor property promotion. #3278431
  4. Use type hints wherever it is possible. #3154762
  5. Omit @var, @param, @return tags for strictly typed values. #3238192
  6. Mark class properties as readonly if they are not ever updated.
  7. Use trailing commas for multiline arrays, methods and annotations.

entity-bundle-class suggestions

  1. Add an All option so that user can generate all bundles for an entity type at once. Also, allow multi-select. These are especially important if we keep writing alter hook implementations. That would be tedious to clean up.
  2. The question text "Would you like to generate a base class?" is problematic. What if I want my bundle class to use an existing base class? Perhaps reword to 'Use a base class?'. That way it doesn't feel like you are overwriting an existing base class, which would be bad.

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.