Skip to content

Instantly share code, notes, and snippets.

@yeknava
Created September 20, 2020 21:37
Show Gist options
  • Save yeknava/c2f0847e8b524fe782b9a58e2d0c99d8 to your computer and use it in GitHub Desktop.
Save yeknava/c2f0847e8b524fe782b9a58e2d0c99d8 to your computer and use it in GitHub Desktop.

Revisions

  1. yeknava created this gist Sep 20, 2020.
    70 changes: 70 additions & 0 deletions publishWithRespect.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    <?php

    use Illuminate\Support\ServiceProvider;

    class SampleServiceProvider extends ServiceProvider {

    public function boot() {
    $this->publishWithRespect([
    dirname(__DIR__, 1) . '/src/Models/' => [
    'path' => config('package.models_path'),
    'old_namespace' => 'Package\\Models',
    'new_namespace' => config('package.models_namespace'),
    ]
    ]);

    /**
    * also supports single file:
    * $this->publishWithRespect([
    * dirname(__DIR__, 1) . '/src/Models/PackageModel.php' => [
    * 'path' => config('simple-shop.models_path').'PackageModel.php',
    * 'old_namespace' => 'Package\\Models',
    * 'new_namespace' => config('package.models_namespace'),
    * ]
    * ]);
    */
    }

    public function publishWithRespect(array $paths) {
    $files = [];
    foreach($paths as $from => $to) {
    if (
    is_array($to) &&
    isset($to['old_namespace']) &&
    isset($to['new_namespace']) &&
    isset($to['path'])
    ) {
    $files = [];
    if ($this->app->get('files')->isDirectory($from)) {
    $allFiles = $this->app->get('files')->files($from);
    foreach($allFiles as $file) {
    $name = $this->app->get('files')->basename($file);
    $files[] = [
    'filename' => $file->getFilename(),
    'path' => $file->getPathname()
    ];
    }
    } else {
    $name = $this->app->get('files')->basename($from);
    $files[] = [
    'filename' => $name,
    'path' => $this->app->get('files')->dirname($from).'/'.$name
    ];
    }
    }
    }

    foreach($files as $file) {
    $newPath = config('simple-shop.models_path').$file['filename'];
    $file = $this->app->get('files')->get($file['path']);
    $this->app->get('files')->put(
    $newPath,
    str_replace(
    $to['old_namespace'],
    $to['new_namespace'],
    $file
    )
    );
    }
    }
    }