Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
bennothommo committed Aug 1, 2022
1 parent 66fc34d commit d255835
Show file tree
Hide file tree
Showing 29 changed files with 2,919 additions and 6 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4
12 changes: 12 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
* text=auto

*.md diff=markdown
*.php diff=php

/.github export-ignore
/tests export-ignore
.editorconfig export-ignore
.gitattributes export-ignore
.gitignore export-ignore
phpstan.neon export-ignore
phpunit.xml.dist export-ignore
69 changes: 69 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
name: Tests

on:
push:
pull_request:

jobs:
phpUnitTests:
strategy:
max-parallel: 6
matrix:
operatingSystem: [ubuntu-latest, windows-latest]
phpVersion: ['7.4', '8.0', '8.1']
fail-fast: false
runs-on: ${{ matrix.operatingSystem }}
name: ${{ matrix.operatingSystem }} / PHP ${{ matrix.phpVersion }}
env:
extensions: curl, fileinfo, gd, mbstring, openssl, pdo, pdo_sqlite, sqlite3, xml, zip
key: winter-cms-cache-develop
steps:
- name: Cancel previous incomplete runs
uses: styfle/[email protected]
with:
access_token: ${{ github.token }}

- name: Checkout changes
uses: actions/checkout@v2

- name: Setup extension cache
id: extcache
uses: shivammathur/cache-extensions@v1
with:
php-version: ${{ matrix.phpVersion }}
extensions: ${{ env.extensions }}
key: ${{ env.key }}

- name: Cache extensions
uses: actions/cache@v2
with:
path: ${{ steps.extcache.outputs.dir }}
key: ${{ steps.extcache.outputs.key }}
restore-keys: ${{ steps.extcache.outputs.key }}

- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.phpVersion }}
extensions: ${{ env.extensions }}

- name: Setup dependency cache
id: composercache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"

- name: Cache dependencies
uses: actions/cache@v2
with:
path: ${{ steps.composercache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }}
restore-keys: ${{ runner.os }}-composer-

- name: Install Composer dependencies
run: composer install --no-interaction --no-progress --no-scripts

- name: Setup problem matchers for PHPUnit
if: matrix.phpVersion == '8.1'
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"

- name: Run tests
run: vendor/bin/phpunit
6 changes: 2 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
composer.phar
/vendor/

# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control
# You may choose to ignore a library lock file http:https://getcomposer.org/doc/02-libraries.md#lock-file
# composer.lock
.phpunit.cache
composer.lock
172 changes: 170 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,170 @@
# laravel-config-writer
Utility to create and update Laravel config and .env files
# Laravel Config Writer

[![Version](https://img.shields.io/github/v/release/wintercms/laravel-config-writer?sort=semver&style=flat-square)](https://github.com/wintercms/laravel-config-writer/releases)
[![Tests](https://img.shields.io/github/workflow/status/wintercms/laravel-config-writer/Tests/develop?label=tests&style=flat-square)](https://github.com/wintercms/laravel-config-writer/actions)
[![License](https://img.shields.io/github/license/winter/laravel-config-writer?label=open%20source&style=flat-square)](https://packagist.org/packages/winter/laravel-config-writer)
[![Discord](https://img.shields.io/discord/816852513684193281?label=discord&style=flat-square)](https://discord.gg/D5MFSPH6Ux)

A utility to easily create and modify Laravel-style PHP configuration files and environment files whilst maintaining the formatting and comments contained within. This utility works by parsing the configuration files using the [PHP Parser library](https://github.com/nikic/php-parser) to convert the configuration into an abstract syntax tree, then carefully modifying the configuration values as required.

This library was originally written as part of the [Storm library](https://github.com/wintercms/storm) in [Winter CMS](https://wintercms.com), but has since been extracted and repurposed as a standalone library.

## Installation

```
composer require winter/laravel-config-writer
```

## Usage

### PHP array files

You can modify Laravel-style PHP configuration files - PHP files that return a single array - by using the `Winter\LaravelConfig\ArrayFile` class. Use the `open` method to open an existing file for modification, or to create a new config file.

```php
use Winter\LaravelConfig\ArrayFile;

$config = ArrayFile::open(base_path('config/app.php'));
```

You can set values using the `set` method. This method can be used fluently, or can be called with a single key and value or an array of keys and values.

```php
$config->set('name', 'Winter CMS');

$config
->set('locale', 'en_US')
->set('fallbackLocale', 'en');

$config->set([
'trustedHosts' => true,
'trustedProxies' => '*',
]);
```

You can also set deep values in an array value by specifying the key in dot notation, or as a nested array.

```php
$config->set('connections.mysql.host', 'localhost');

$config->set([
'connections' => [
'sqlite' => [
'database' => 'database.sqlite',
'driver' => 'sqlite',
'foreign_key_constraints' => true,
'prefix' => '',
'url' => null,
],
],
]);
```

To finalise all your changes, use the `write` method to write the changes to the open file.

```php
$config->write();
```

If desired, you may also write the changes to another file altogether.

```php
$config->write('path/to/newfile.php');
```

Or you can simply render the changes as a string.

```php
$config->render();
```

#### Function calls as values

Function calls can be added to your configuration file by using the `function` method. The first parameter of the `function` method defines the function to call, and the second parameter accepts an array of parameters to provide to the function.

```php
$config->set('name', $config->function('env', ['APP_NAME', 'Winter CMS']));
```

#### Constants as values

Constants can be added to your configuration file by using the `constant` method. The only parameter required is the name of the constant.

```php
$config->set('foo.bar', $config->constant('My\Class::CONSTANT'));
```

#### Sorting the configuration file

You can sort the configuration keys alphabetically by using the `sort` method. This will sort all current configuration values.

```php
$config->sort();
```

By default, this will sort the keys alphabetically in ascending order. To sort in the opposite direction, include the `ArrayFile::SORT_DESC` parameter.

```php
$config->sort(ArrayFile::SORT_DESC);
```

### Environment files

This utility library also allows manipulation of environment files, typically found as `.env` files in a project. The `Winter\LaravelConfig\EnvFile::open()` method allows you to open or create an environment file for modification.

```php
use Winter\LaravelConfig\EnvFile;

$config = EnvFile::open(base_path('.env'));
```

You can set values using the `set` method. This method can be used fluently, or can be called with a single key and value or an array of keys and values.

```php
$config->set('APP_NAME', 'Winter CMS');

$config
->set('APP_URL', 'https://wintercms.com')
->set('APP_ENV', 'production');

$config->set([
'DB_CONNECTION' => 'sqlite',
'DB_DATABASE' => 'database.sqlite',
]);
```

> **Note:** Arrays are not supported in environment files.
You can add an empty line into the environment file by using the `addEmptyLine` method. This allows you to separate groups of environment variables.

```php
$env->set('FOO', 'bar');
$env->addEmptyLine();
$env->set('BAR', 'foo');
```

To finalise all your changes, use the `write` method to write the changes to the open file.

```php
$config->write();
```

If desired, you may also write the changes to another file altogether.

```php
$config->write(base_path('.env.local'));
```

Or you can simply render the changes as a string.

```php
$config->render();
```

## License

This utility library is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

## Security vulnerabilities

Please review our [security policy](https://github.com/wintercms/winter/security/policy) on how to report security vulnerabilities.
36 changes: 36 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "winter/laravel-config-writer",
"description": "Utility to create and update Laravel config and .env files",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Jack Wilkinson",
"email": "[email protected]",
"role": "Original author"
},
{
"name": "Winter CMS Maintainers",
"homepage": "https://wintercms.com",
"role": "Maintainers"
}
],
"require": {
"php": "^7.4.0 || ^8.0",
"nikic/php-parser": "^4.10"
},
"require-dev": {
"phpstan/phpstan": "^1.6",
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {
"Winter\\LaravelConfig\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Winter\\LaravelConfig\\Tests\\": "tests/"
}
}
}
47 changes: 47 additions & 0 deletions phpcs.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?xml version="1.0"?>
<ruleset name="Winter CMS">
<description>The coding standard for Winter CMS.</description>
<rule ref="PSR2">
<!--
Exceptions to the PSR-2 guidelines as per our Developer Guide:
https://wintercms.com/help/guidelines/developer#psr-exceptions
-->
<exclude name="PSR1.Methods.CamelCapsMethodName.NotCamelCaps" />
<exclude name="Squiz.ControlStructures.ControlSignature.SpaceAfterCloseBrace" />
<exclude name="PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace" />

<!-- We're not enforcing a line length limit -->
<exclude name="Generic.Files.LineLength" />
</rule>

<rule ref="Squiz.ControlStructures.ControlSignature">
<!-- We use 0 spaces before the colon for short (alternative) tags -->
<properties>
<property name="requiredSpacesBeforeColon" value="0" />
</properties>
</rule>

<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<!-- Tests do not need a namespace defined -->
<exclude-pattern>*/tests/*</exclude-pattern>
</rule>

<rule ref="PSR1.Classes.ClassDeclaration.MultipleClasses">
<!--
Test fixtures and cases can have multiple classes defined, only if they are directly related to the test, or are
extended classes
-->
<exclude-pattern>*/tests/*</exclude-pattern>
</rule>

<arg name="extensions" value="php" />
<arg name="colors" />

<file>src/</file>
<file>tests/</file>

<!-- Ignore vendor files -->
<exclude-pattern>*/vendor/*</exclude-pattern>
<!-- Ignore test fixtures -->
<exclude-parrent>tests/fixtures/*</exclude-pattern>
</ruleset>
7 changes: 7 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
parameters:
level: 6
paths:
- src
ignoreErrors:
- message: '#Access to an undefined property.*?\$expr#'
path: src/ArrayFile.php
28 changes: 28 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http:https://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
bootstrap="tests/bootstrap.php"
cacheResultFile=".phpunit.cache/test-results"
executionOrder="depends,defects"
forceCoversAnnotation="false"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
failOnWarning="true"
>
<testsuites>
<testsuite name="Test Suite">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>

<coverage
cacheDirectory=".phpunit.cache/code-coverage"
processUncoveredFiles="true"
>
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
</phpunit>
Loading

0 comments on commit d255835

Please sign in to comment.