phpro / grumphp

A PHP code-quality tool
MIT License
4.11k stars 429 forks source link

Best way to provide an API token to an extension #1040

Closed benr77 closed 1 year ago

benr77 commented 1 year ago
Q A
Version 1.13.0
Bug? no
New feature? no
Question? yes
Documentation? no
Related tickets

I have just built an extension to lint Gitlab CI configuration yaml files.

https://github.com/headsnet/grumphp-gitlab-lint

One thing that is bugging me is that it requires a Gitlab API token, and currently my extension expects this token to be provided via the grumphp.yml config file. However, it's not great as this file will be committed to the repo and we don't want tokens committed!

So I'm looking at an alternative way to provide the token via an environment variable instead.

What is the best way to access the environment variable from the extension code? Obviously we have getenv() but I'm wondering if GrumPHP already has a method to import and access?

Thanks!

veewee commented 1 year ago

Hello,

This package uses symfony/dependency-injection and symfony/dotenv.

If you want to inject the env var through the yaml file, you can use '%env(XXX)%' in the grumphp.yaml file. Another way is by using the global $_ENV or the non-threadsafe getenv function.

See https://symfony.com/doc/current/configuration/env_var_processors.html

benr77 commented 1 year ago

Awesome thanks for the quick response !!

benr77 commented 1 year ago

Sorry one more question - can you confirm if it will automatically pick up vars from multiple .env files such as .env.test ? I can't see how the $config array is populated in GrumPHP\Configuration\Environment\DotEnvRegistrar.

I have a standard Symfony project with multiple .env files.

Thanks again!

veewee commented 1 year ago

It is provided through the configuration https://github.com/phpro/grumphp/blob/master/doc/parameters.md

You can define dotenv files or per variable in there.

benr77 commented 1 year ago

I have encountered a strange issue trying to get this setup. Instead of making the actual value of my GITLAB_TOKEN env var available, I get a strange string which looks like env_e7937a168f382d27_GITLAB_TOKEN_4e06944bcec1f665r4a82bf0125e3f8d.

# .env.local

GITLAB_TOKEN=XXXXXX
# grumphp.yml

grumphp:
    tasks:
        gitlab_lint:
            api_token: '%env(GITLAB_TOKEN)%'
    environment:
        files:
            - .env.local

Any pointers much appreciated. Thank you.