[
  {
    "path": ".gitattributes",
    "content": "/.gitattributes export-ignore\n/.gitignore export-ignore\n/.styleci.yml export-ignore\n/phpunit.xml.dist export-ignore\n/tests export-ignore\n/.travis.yml export-ignore"
  },
  {
    "path": ".github/workflows/run-php-cs-fixer.yml",
    "content": "name: Fix PHP Code Style\n\non:\n  workflow_dispatch:\n  push:\n    paths:\n      - '**.php'\n\njobs:\n  fix-php-code-style:\n    name: Fix PHP Code Style\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n        with:\n          fetch-depth: 2\n          token: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Run PHP CS Fixer\n        uses: docker://oskarstark/php-cs-fixer-ga:2.18.6\n\n      - name: Commit changes\n        uses: stefanzweifel/git-auto-commit-action@v4\n        with:\n          commit_message: Fix Backend Code Style\n          skip_fetch: true\n"
  },
  {
    "path": ".github/workflows/run-tests.yml",
    "content": "name: Run Tests\n\non: [push]\n\njobs:\n  test:\n\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        php: [8.1, 8.0]\n        laravel: [9.*]\n        dependency-version: [prefer-lowest, prefer-stable]\n        include:\n          - laravel: 9.*\n            testbench: 7.*\n\n    name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }}\n\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v1\n\n      - name: Cache dependencies\n        uses: actions/cache@v1\n        with:\n          path: ~/.composer/cache/files\n          key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }}\n\n      - name: Setup PHP\n        uses: shivammathur/setup-php@v2\n        with:\n          php-version: ${{ matrix.php }}\n          extensions: mbstring\n\n      - name: Install dependencies\n        run: |\n          composer require \"laravel/framework:${{ matrix.laravel }}\" \"orchestra/testbench:${{ matrix.testbench }}\" --no-interaction --no-update\n          composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest\n\n      - name: Execute tests\n        run: vendor/bin/phpunit\n"
  },
  {
    "path": ".gitignore",
    "content": ".idea\nvendor\ncomposer.lock\n/phpunit.xml\n.phpunit.result.cache\n.php_cs.cache"
  },
  {
    "path": ".php_cs",
    "content": "<?php\n\n$finder = Symfony\\Component\\Finder\\Finder::create()\n    ->notPath('spark')\n    ->notPath('bootstrap')\n    ->notPath('storage')\n    ->notPath('vendor')\n    ->in(__DIR__)\n    ->name('*.php')\n    ->name('_ide_helper')\n    ->notName('*.blade.php')\n    ->ignoreDotFiles(true)\n    ->ignoreVCS(true);\n\n\nreturn PhpCsFixer\\Config::create()\n    ->setRules([\n        '@PSR2' => true,\n        'array_syntax' => ['syntax' => 'short'],\n        'ordered_imports' => ['sortAlgorithm' => 'alpha'],\n        'no_unused_imports' => true,\n    ])\n    ->setFinder($finder);"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nContributions are **welcome** and will be fully **credited**.\n\nPlease read and understand the contribution guide before creating an issue or pull request.\n\n## Requirements\n\nIf the project maintainer has any additional requirements, you will find them listed here.\n\n\n- **[PSR-2 Coding Standard.](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** The easiest way to apply the conventions is to install [PHP CS Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer).\n- **Add tests!** Your patch won't be accepted if it doesn't have tests.\n- **Document any change in behaviour.** Make sure the `README.md` and any other relevant documentation are kept up-to-date.\n- **Consider our release cycle.** We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.\n- **Create feature branches.** Don't ask us to pull from your master branch.\n- **One pull request per feature.** If you want to do more than one thing, send multiple pull requests.\n- **Send coherent history.** Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.\n\n**Happy coding!**\n"
  },
  {
    "path": "LICENSE.md",
    "content": "MIT License\n\nCopyright (c) 2018 Coderello\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Laravel Shared Data\n\n## ✨ Introduction\n\n**Laravel Shared Data** provides an easy way to share the data from your backend to the JavaScript.\n\n## 🚀 Quick start\n\n-   Install the package:\n    ```bash\n    composer require coderello/laravel-shared-data\n    ```\n\n-   Include the `@shared` directive into your blade layout before all scripts.\n\n-   Share the data from within Laravel:\n    ```bash\n    share(['user' => $user, 'title' => $title]);\n    ```\n    \n-   Access the data from the JavaScript directly:\n    ```bash\n    const user = window.sharedData.user;\n    const title = window.sharedData.title;\n    ```\n    \n-   Or using the built-it global helper:\n    ```bash\n    const user = shared('user');\n    const title = shared('title');\n    ```\n\n## 📖 License\n\n**Laravel Shared Data** is open-sourced software licensed under the [MIT license](LICENSE.md).\n"
  },
  {
    "path": "composer.json",
    "content": "{\n    \"name\": \"coderello/laravel-shared-data\",\n    \"description\": \"Package for sharing data from Laravel to JavaScript.\",\n    \"type\": \"library\",\n    \"license\": \"MIT\",\n    \"require\": {\n        \"php\": \"^8.0\",\n        \"ext-json\": \"*\",\n        \"illuminate/support\": \"^9.0\"\n    },\n    \"require-dev\": {\n        \"orchestra/testbench\": \"^7.0\"\n    },\n    \"autoload\": {\n        \"psr-4\": {\n            \"Coderello\\\\SharedData\\\\\": \"src/\"\n        },\n        \"files\": [\n            \"src/helpers.php\"\n        ]\n    },\n    \"autoload-dev\": {\n        \"psr-4\": {\n            \"Coderello\\\\SharedData\\\\Tests\\\\\": \"tests/\"\n        }\n    },\n    \"scripts\": {\n        \"test\": \"./vendor/bin/phpunit --colors=always\"\n    },\n    \"extra\": {\n        \"laravel\": {\n            \"providers\": [\n                \"Coderello\\\\SharedData\\\\Providers\\\\SharedDataServiceProvider\"\n            ]\n        }\n    },\n    \"config\": {\n        \"sort-packages\": true\n    },\n    \"minimum-stability\": \"dev\",\n    \"prefer-stable\": true\n}\n"
  },
  {
    "path": "config/shared-data.php",
    "content": "<?php\n/**\n * @see https://github.com/coderello/laravel-shared-data\n */\n\nreturn [\n\n    /*\n     * JavaScript namespace.\n     *\n     * By default the namespace is equal to 'sharedData'.\n     *\n     * It means that the shared data will be accessible from `window.sharedData`\n     */\n    'js_namespace' => 'sharedData',\n\n    /*\n     * The settings for the JavaScript helper function that allows\n     * retrieving the shared data on the front-end side easily.\n     *\n     * Example: `shared('user.email')`\n     */\n    'js_helper' => [\n        /*\n         * Determines whether the JavaScript helper should be included\n         * alongside with the shared data.\n         */\n        'enabled' => true,\n\n        /*\n         * The function name for the JavaScript helper.\n         */\n        'name' => 'shared',\n    ],\n\n    /*\n     * The settings for the Blade directive.\n     */\n    'blade_directive' => [\n        /*\n         * Blade directive name.\n         *\n         * By default the Blade directive named 'shared'.\n         *\n         * It means that the shared data rendering will be available in view files via `@shared`.\n         */\n        'name' => 'shared',\n    ],\n];\n"
  },
  {
    "path": "docs/contributing.md",
    "content": "---\ntitle: Contribution Guide\nsection: Contributing\nweight: 100\nfeatherIcon: github\n---\n\nContributions are **welcome** and will be fully **credited**.\n\nPlease read and understand the contribution guide before creating an issue or pull request.\n\n## Requirements\n\nIf the project maintainer has any additional requirements, you will find them listed here.\n\n\n- **[PSR-2 Coding Standard.](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** The easiest way to apply the conventions is to install [PHP CS Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer).\n- **Add tests!** Your patch won't be accepted if it doesn't have tests.\n- **Document any change in behaviour.** Make sure the `README.md` and any other relevant documentation are kept up-to-date.\n- **Consider our release cycle.** We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.\n- **Create feature branches.** Don't ask us to pull from your master branch.\n- **One pull request per feature.** If you want to do more than one thing, send multiple pull requests.\n- **Send coherent history.** Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.\n\n**Happy coding!**\n"
  },
  {
    "path": "docs/installation.md",
    "content": "---\ntitle: Installation\nsection: Getting Started\nweight: 5000\nfeatherIcon: download\n---\n\nYou can install this package via composer using this command:\n\n```bash\ncomposer require coderello/laravel-shared-data \n```\n\nAfter the installation you need to include `@shared` directive into your blade layout before all `<script>` tags.\n\n![@shared directive]({{assets}}/shared-directive.png)\n\n## Publishing the config\n\nTo publish the config file to `config/shared-data.php` run:\n\n```bash\nphp artisan vendor:publish --provider=\"Coderello\\SharedData\\Providers\\SharedDataServiceProvider\" --tag=\"config\"\n```\n"
  },
  {
    "path": "docs/javascript-helper.md",
    "content": "---\ntitle: JavaScript helper\nsection: Getting Started\nweight: 800\nfeatherIcon: coffee\n---\n\nTBD"
  },
  {
    "path": "docs/sharing-data.md",
    "content": "---\ntitle: Sharing data\nsection: Getting Started\nweight: 900\nfeatherIcon: package\n---\n\nYou can share any data you want from any part or your application (middleware, controller, service provider etc.)\n\n```php\nuse Coderello\\SharedData\\Facades\\SharedData;\n\n// using the facade\nSharedData::put([\n    'user' => auth()->user(),\n    'post' => Post::first(),\n    'app' => [\n        'name' => config('app.name'),\n        'environment' => config('app.env'),\n    ],\n]);\n\n// using the helper\nshare([\n    'user' => auth()->user(),\n    'post' => Post::first(),\n    'app' => [\n        'name' => config('app.name'),\n        'environment' => config('app.env'),\n    ],\n]);\n```\n\nAnd get this data on the frontend side directly from `window.sharedData` (use can modify the namespace in the config file) like so:\n\n```js\nconst user = window.sharedData.user;\n```\n\nOr using the global built-in helper:\n```js\nconst user = shared('user');\n```\n\n> You can get more info on the global built-in helper on the [JavaScript helper]({{base}}/{{version}}/javascript-helper) page.\n\n![console.log(window.sharedData);]({{assets}}/window-shared-data.png)\n"
  },
  {
    "path": "phpunit.xml.dist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit backupGlobals=\"false\"\n         backupStaticAttributes=\"false\"\n         beStrictAboutTestsThatDoNotTestAnything=\"false\"\n         bootstrap=\"vendor/autoload.php\"\n         colors=\"true\"\n         convertErrorsToExceptions=\"true\"\n         convertNoticesToExceptions=\"true\"\n         convertWarningsToExceptions=\"true\"\n         processIsolation=\"false\"\n         stopOnFailure=\"false\"\n>\n    <testsuites>\n        <testsuite name=\"Laravel Shared Data Test Suite\">\n            <directory suffix=\".php\">./tests/</directory>\n        </testsuite>\n    </testsuites>\n    <filter>\n        <whitelist processUncoveredFilesFromWhitelist=\"true\">\n            <directory suffix=\".php\">./src/</directory>\n        </whitelist>\n    </filter>\n</phpunit>"
  },
  {
    "path": "src/Facades/SharedData.php",
    "content": "<?php\n\nnamespace Coderello\\SharedData\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\n/**\n * @see \\Coderello\\SharedData\\SharedData\n *\n * @method static \\Coderello\\SharedData\\SharedData put(mixed $key, mixed $value = null)\n * @method static mixed get(mixed $key = null)\n * @method static string toJson(int $options = 0)\n * @method static string render()\n */\nclass SharedData extends Facade\n{\n    /**\n     * {@inheritdoc}\n     */\n    protected static function getFacadeAccessor()\n    {\n        return \\Coderello\\SharedData\\SharedData::class;\n    }\n}\n"
  },
  {
    "path": "src/Providers/SharedDataServiceProvider.php",
    "content": "<?php\n\nnamespace Coderello\\SharedData\\Providers;\n\nuse Coderello\\SharedData\\SharedData;\nuse Illuminate\\Contracts\\Support\\DeferrableProvider;\nuse Illuminate\\Support\\ServiceProvider;\nuse Illuminate\\View\\Compilers\\BladeCompiler;\n\nclass SharedDataServiceProvider extends ServiceProvider implements DeferrableProvider\n{\n    /**\n     * Bootstrap shared data service.\n     *\n     * @return void\n     */\n    public function boot()\n    {\n        $this->publishes([\n            __DIR__.'/../../config/shared-data.php' => config_path('shared-data.php'),\n        ], 'shared-data-config');\n    }\n\n    /**\n     * Register any application services.\n     *\n     * @return void\n     */\n    public function register()\n    {\n        $this->mergeConfigFrom(\n            __DIR__.'/../../config/shared-data.php',\n            'shared-data'\n        );\n\n        $this->app->singleton(SharedData::class, function () {\n            return new SharedData($this->app['config']['shared-data']);\n        });\n\n        $this->app->extend('blade.compiler', function (BladeCompiler $bladeCompiler) {\n            $bladeCompiler->directive($this->app['config']['shared-data.blade_directive.name'] ?? 'shared', function () {\n                return '<?php echo app(\\\\'.SharedData::class.'::class)->render(); ?>';\n            });\n\n            return $bladeCompiler;\n        });\n    }\n\n    /**\n     * Get the services provided by the provider.\n     *\n     * @return array\n     */\n    public function provides()\n    {\n        return [\n            SharedData::class,\n            'blade.compiler'\n        ];\n    }\n}\n"
  },
  {
    "path": "src/SharedData.php",
    "content": "<?php\n\nnamespace Coderello\\SharedData;\n\nuse ArrayAccess;\nuse Closure;\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse Illuminate\\Contracts\\Support\\Jsonable;\nuse Illuminate\\Contracts\\Support\\Renderable;\nuse Illuminate\\Support\\Arr;\nuse InvalidArgumentException;\nuse JsonSerializable;\n\nclass SharedData implements Renderable, Jsonable, Arrayable, JsonSerializable, ArrayAccess\n{\n    /** @var array */\n    private $data = [];\n\n    /** @var string */\n    private $jsNamespace = 'sharedData';\n\n    /** @var bool */\n    private $jsHelperEnabled = true;\n\n    /** @var string */\n    private $jsHelperName = 'shared';\n\n    /** @var Closure[]|array */\n    private $delayedClosures = [];\n\n    /** @var Closure[]|array */\n    private $delayedClosuresWithKeys = [];\n\n    public function __construct(array $config = [])\n    {\n        $this->hydrateConfig($config);\n    }\n\n    private function hydrateConfig(array $config)\n    {\n        if (Arr::has($config, 'js_namespace')) {\n            $this->setJsNamespace(Arr::get($config, 'js_namespace'));\n        }\n\n        if (Arr::has($config, 'js_helper.enabled')) {\n            $this->setJsHelperEnabled(Arr::get($config, 'js_helper.enabled'));\n        }\n\n        if (Arr::has($config, 'js_helper.name')) {\n            $this->setJsHelperName(Arr::get($config, 'js_helper.name'));\n        }\n    }\n\n    private function unpackDelayedClosures(): self\n    {\n        foreach ($this->delayedClosures as $delayedClosure) {\n            $this->put($delayedClosure());\n        }\n\n        $this->delayedClosures = [];\n\n        foreach ($this->delayedClosuresWithKeys as $key => $delayedClosure) {\n            $this->put($key, $delayedClosure());\n        }\n\n        $this->delayedClosuresWithKeys = [];\n\n        return $this;\n    }\n\n    public function put($key, $value = null)\n    {\n        if (is_scalar($key) && $value instanceof Closure) {\n            $this->delayedClosuresWithKeys[$key] = $value;\n        } elseif (is_scalar($key)) {\n            Arr::set($this->data, $key, $value);\n        } elseif (is_iterable($key)) {\n            foreach ($key as $nestedKey => $nestedValue) {\n                $this->put($nestedKey, $nestedValue);\n            }\n        } elseif ($key instanceof JsonSerializable) {\n            $this->put($key->jsonSerialize());\n        } elseif ($key instanceof Arrayable) {\n            $this->put($key->toArray());\n        } elseif ($key instanceof Closure) {\n            $this->delayedClosures[] = $key;\n        } elseif (is_object($key)) {\n            $this->put(get_object_vars($key));\n        } else {\n            throw new InvalidArgumentException('Key type ['.gettype($key).'] is not supported.');\n        }\n\n        return $this;\n    }\n\n    public function get($key = null)\n    {\n        $this->unpackDelayedClosures();\n\n        if (is_null($key)) {\n            return $this->data;\n        }\n\n        return Arr::get($this->data, $key);\n    }\n\n    public function forget($key = null): self\n    {\n        $this->unpackDelayedClosures();\n\n        if (is_null($key)) {\n            $this->data = [];\n        } else {\n            Arr::forget($this->data, $key);\n        }\n\n        return $this;\n    }\n\n    public function getJsNamespace(): string\n    {\n        return $this->jsNamespace;\n    }\n\n    public function setJsNamespace(string $jsNamespace): self\n    {\n        $this->jsNamespace = $jsNamespace;\n\n        return $this;\n    }\n\n    public function getJsHelperEnabled(): bool\n    {\n        return $this->jsHelperEnabled;\n    }\n\n    public function setJsHelperEnabled(bool $jsHelperEnabled): self\n    {\n        $this->jsHelperEnabled = $jsHelperEnabled;\n\n        return $this;\n    }\n\n    public function getJsHelperName(): string\n    {\n        return $this->jsHelperName;\n    }\n\n    public function setJsHelperName(string $jsHelperName): self\n    {\n        $this->jsHelperName = $jsHelperName;\n\n        return $this;\n    }\n\n    public function toJson($options = 0): string\n    {\n        return json_encode($this->get(), $options);\n    }\n\n    public function render(array $options = []): string\n    {\n        $attributes = $options['attributes'] ?? [];\n\n        $attributeStrings = [];\n\n        foreach ($attributes as $attributeName => $attributeValue) {\n            $attributeStrings[] = $attributeName.'=\"'.htmlentities($attributeValue, ENT_QUOTES, 'UTF-8', false).'\"';\n        }\n\n        return (count($attributeStrings) === 0 ? '<script>' : '<script '.implode(' ', $attributeStrings).'>')\n            .'window[\"'.$this->getJsNamespace().'\"]='.$this->toJson().';'\n            .'window[\"sharedDataNamespace\"]=\"'.$this->getJsNamespace().'\";'\n            .($this->getJsHelperEnabled() ? $this->getJsHelper().';' : '')\n            .'</script>';\n    }\n\n    public function getJsHelper(): string\n    {\n        return 'window[\"'.$this->getJsHelperName().'\"]=function(e){var n=void 0!==arguments[1]?arguments[1]:null;return[window.sharedDataNamespace].concat(\"string\"==typeof e?e.split(\".\"):[]).reduce(function(e,t){return e===n||\"object\"!=typeof e||void 0===e[t]?n:e[t]},window)}';\n    }\n\n    public function __toString(): string\n    {\n        return $this->render();\n    }\n\n    public function toArray(): array\n    {\n        return $this->get();\n    }\n\n    public function jsonSerialize(): array\n    {\n        return $this->get();\n    }\n\n    public function offsetExists($offset): bool\n    {\n        return Arr::has($this->data, $offset);\n    }\n\n    public function offsetGet($offset)\n    {\n        return $this->get($offset);\n    }\n\n    public function offsetSet($offset, $value): void\n    {\n        $this->put($offset, $value);\n    }\n\n    public function offsetUnset($offset): void\n    {\n        $this->forget($offset);\n    }\n}\n"
  },
  {
    "path": "src/helpers.php",
    "content": "<?php\n\nif (! function_exists('shared')) {\n    /**\n     * @return \\Coderello\\SharedData\\SharedData\n     */\n    function shared()\n    {\n        return app(\\Coderello\\SharedData\\SharedData::class);\n    }\n}\n\nif (! function_exists('share')) {\n    /**\n     * @param array $args\n     * @return \\Coderello\\SharedData\\SharedData\n     */\n    function share(...$args)\n    {\n        return app(\\Coderello\\SharedData\\SharedData::class)->put(...$args);\n    }\n}\n"
  },
  {
    "path": "tests/AbstractTestCase.php",
    "content": "<?php\n\nnamespace Coderello\\SharedData\\Tests;\n\nuse Coderello\\SharedData\\Providers\\SharedDataServiceProvider;\nuse Orchestra\\Testbench\\TestCase;\n\nabstract class AbstractTestCase extends TestCase\n{\n    protected function setUp(): void\n    {\n        parent::setUp();\n\n        view()->addLocation(__DIR__.'/views');\n    }\n\n    protected function getPackageProviders($app)\n    {\n        return [\n            SharedDataServiceProvider::class,\n        ];\n    }\n}\n"
  },
  {
    "path": "tests/SharedDataTest.php",
    "content": "<?php\n\nnamespace Coderello\\SharedData\\Tests;\n\nuse Coderello\\SharedData\\SharedData;\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse JsonSerializable;\nuse stdClass;\n\nclass SharedDataTest extends AbstractTestCase\n{\n    /** @var SharedData|null */\n    protected $sharedData;\n\n    /** @var mixed|null */\n    protected $lazy;\n\n    protected function setUp(): void\n    {\n        parent::setUp();\n\n        $this->sharedData = new SharedData;\n\n        $this->lazy = null;\n    }\n\n    public function testPut()\n    {\n        // scalar\n\n        $this->sharedData->put('foo', 'bar');\n\n        $this->assertSame('bar', $this->sharedData->get('foo'));\n\n        // iterable\n\n        $this->sharedData->put([\n            'scalar' => 'scalar-value',\n            'array' => ['nested' => 'value'],\n        ]);\n\n        $this->assertSame('scalar-value', $this->sharedData->get('scalar'));\n\n        $this->assertSame(['nested' => 'value'], $this->sharedData->get('array'));\n\n        // JsonSerializable\n\n        $jsonSerializable = new class implements JsonSerializable {\n            public function jsonSerialize()\n            {\n                return [\n                    'json-serializable-key' => 'json-serializable-value',\n                ];\n            }\n        };\n\n        $this->sharedData->put($jsonSerializable);\n\n        $this->assertSame('json-serializable-value', $this->sharedData->get('json-serializable-key'));\n\n        // Arrayable\n\n        $arrayable = new class implements Arrayable {\n            public function toArray()\n            {\n                return [\n                    'arrayable-key' => 'arrayable-value',\n                ];\n            }\n        };\n\n        $this->sharedData->put($arrayable);\n\n        $this->assertSame('arrayable-value', $this->sharedData->get('arrayable-key'));\n\n        // Closure (lazy)\n\n        $this->lazy = 'foo';\n\n        $this->sharedData->put(function () {\n            return [\n                'lazy' => $this->lazy,\n            ];\n        });\n\n        $this->lazy = 'bar';\n\n        $this->assertSame('bar', $this->sharedData->get('lazy'));\n\n        // Closure (lazy) with key\n\n        $this->lazy = 'foo';\n\n        $this->sharedData->put('lazy-with-key', function () {\n            return $this->lazy;\n        });\n\n        $this->lazy = 'bar';\n\n        $this->assertSame('bar', $this->sharedData->get('lazy-with-key'));\n\n        // object\n\n        $object = new stdClass;\n\n        $object->objectScalar = 'object-scalar';\n\n        $object->objectArray = ['nested' => 'object-scalar'];\n\n        $this->sharedData->put($object);\n\n        $this->assertSame('object-scalar', $this->sharedData->get('objectScalar'));\n\n        $this->assertSame(['nested' => 'object-scalar'], $this->sharedData->get('objectArray'));\n    }\n\n    public function testGet()\n    {\n        $values = [\n            'scalar' => 'scalar-value',\n            'array' => ['nested' => 'value'],\n        ];\n\n        $this->sharedData->put($values);\n\n        $this->assertSame('scalar-value', $this->sharedData->get('scalar'));\n\n        $this->assertSame($values, $this->sharedData->get());\n    }\n\n    public function testToJson()\n    {\n        $this->sharedData->put([\n            'scalar' => 'scalar-value',\n            'array' => ['nested' => 'value'],\n        ]);\n\n        $json = $this->sharedData->toJson();\n\n        $expectedJson = '{\"scalar\":\"scalar-value\",\"array\":{\"nested\":\"value\"}}';\n\n        $this->assertSame($expectedJson, $json);\n    }\n\n    public function testRender()\n    {\n        $this->sharedData->put([\n            'scalar' => 'scalar-value',\n            'array' => ['nested' => 'value'],\n        ]);\n\n        $this->sharedData->setJsNamespace('customShareDataNamespace');\n\n        $this->sharedData->setJsHelperName('customSharedFunctionName');\n\n        $this->sharedData->setJsHelperEnabled(true);\n\n        $html = $this->sharedData->render();\n\n        $expectedHtml = '<script>window[\"customShareDataNamespace\"]={\"scalar\":\"scalar-value\",\"array\":{\"nested\":\"value\"}};window[\"sharedDataNamespace\"]=\"customShareDataNamespace\";window[\"customSharedFunctionName\"]=function(e){var n=void 0!==arguments[1]?arguments[1]:null;return[window.sharedDataNamespace].concat(\"string\"==typeof e?e.split(\".\"):[]).reduce(function(e,t){return e===n||\"object\"!=typeof e||void 0===e[t]?n:e[t]},window)};</script>';\n\n        $this->assertSame($expectedHtml, $html);\n    }\n\n    public function testRenderWithAttributes()\n    {\n        $this->sharedData->put([\n            'scalar' => 'scalar-value',\n            'array' => ['nested' => 'value'],\n        ]);\n\n        $this->sharedData->setJsNamespace('customShareDataNamespace');\n\n        $this->sharedData->setJsHelperName('customSharedFunctionName');\n\n        $this->sharedData->setJsHelperEnabled(true);\n\n        $html = $this->sharedData->render(['attributes' => ['nonce' => 'HELLOWORLD\">', 'data-hello' => 'world']]);\n\n        $expectedHtml = '<script nonce=\"HELLOWORLD&quot;&gt;\" data-hello=\"world\">window[\"customShareDataNamespace\"]={\"scalar\":\"scalar-value\",\"array\":{\"nested\":\"value\"}};window[\"sharedDataNamespace\"]=\"customShareDataNamespace\";window[\"customSharedFunctionName\"]=function(e){var n=void 0!==arguments[1]?arguments[1]:null;return[window.sharedDataNamespace].concat(\"string\"==typeof e?e.split(\".\"):[]).reduce(function(e,t){return e===n||\"object\"!=typeof e||void 0===e[t]?n:e[t]},window)};</script>';\n\n        $this->assertSame($expectedHtml, $html);\n    }\n\n    public function testToString()\n    {\n        $this->sharedData->put('foo', 'bar');\n\n        $this->assertSame($this->sharedData->render(), (string) $this->sharedData);\n    }\n\n    public function testJsNamespace()\n    {\n        $this->assertSame('sharedData', $this->sharedData->getJsNamespace());\n\n        $this->sharedData->setJsNamespace('foo');\n\n        $this->assertSame('foo', $this->sharedData->getJsNamespace());\n    }\n\n    public function testJsHelperName()\n    {\n        $this->assertSame('shared', $this->sharedData->getJsHelperName());\n\n        $this->sharedData->setJsHelperName('customShared');\n\n        $this->assertSame('customShared', $this->sharedData->getJsHelperName());\n    }\n\n    public function testJsHelperEnabled()\n    {\n        $this->assertSame(true, $this->sharedData->getJsHelperEnabled());\n\n        $this->sharedData->setJsHelperEnabled(false);\n\n        $this->assertSame(false, $this->sharedData->getJsHelperEnabled());\n    }\n\n    public function testJsHelper()\n    {\n        $this->sharedData->setJsHelperName('customSharedFunctionName');\n\n        $this->assertSame('window[\"customSharedFunctionName\"]=function(e){var n=void 0!==arguments[1]?arguments[1]:null;return[window.sharedDataNamespace].concat(\"string\"==typeof e?e.split(\".\"):[]).reduce(function(e,t){return e===n||\"object\"!=typeof e||void 0===e[t]?n:e[t]},window)}', $this->sharedData->getJsHelper());\n    }\n\n    public function testToArray()\n    {\n        $this->sharedData->put('foo', ['bar' => 'baz']);\n\n        $this->assertSame(['foo' => ['bar' => 'baz']], $this->sharedData->toArray());\n    }\n\n    public function testJsonSerialize()\n    {\n        $this->sharedData->put('foo', ['bar' => 'baz']);\n\n        $this->assertSame(['foo' => ['bar' => 'baz']], $this->sharedData->jsonSerialize());\n    }\n\n    public function testOffsetExists()\n    {\n        $this->sharedData->put('foo.baz', 'bar');\n\n        $this->assertTrue(isset($this->sharedData['foo.baz']));\n\n        $this->assertFalse(isset($this->sharedData['baz.foo']));\n    }\n\n    public function testOffsetGet()\n    {\n        $this->sharedData->put('foo.bar', 'baz');\n\n        $this->assertSame('baz', $this->sharedData['foo.bar']);\n    }\n\n    public function testOffsetSet()\n    {\n        $this->sharedData['foo.bar'] = 'baz';\n\n        $this->assertSame(\n            [\n                'foo' => [\n                    'bar' => 'baz',\n                ],\n            ],\n            $this->sharedData->get()\n        );\n    }\n\n    public function testOffsetUnset()\n    {\n        $this->sharedData->put([\n            'foo' => [\n                'bar' => 'baz',\n                'baz' => 'bar',\n            ],\n        ]);\n\n        unset($this->sharedData['foo.baz']);\n\n        $this->assertSame(\n            [\n                'foo' => [\n                    'bar' => 'baz',\n                ],\n            ],\n            $this->sharedData->get()\n        );\n    }\n\n    public function testForget()\n    {\n        $this->sharedData->put([\n            'foo' => [\n                'bar' => 'baz',\n                'baz' => 'bar',\n            ],\n        ]);\n\n        $this->sharedData->forget('foo.baz');\n\n        $this->assertSame(\n            [\n                'foo' => [\n                    'bar' => 'baz',\n                ],\n            ],\n            $this->sharedData->get()\n        );\n\n        $this->sharedData->forget();\n\n        $this->assertSame([], $this->sharedData->get());\n    }\n\n    public function testBladeDirective()\n    {\n        $this->assertEquals(\n            shared()->render(),\n            view('shared')->render()\n        );\n    }\n\n    /**\n     * @depends testBladeDirective\n     */\n    public function testBladeDirectiveWithCustomName()\n    {\n        $this->app['config']['shared-data.blade_directive.name'] = 'shared_custom';\n\n        $this->assertEquals(\n            shared()->render(),\n            view('shared_custom')->render()\n        );\n    }\n}\n"
  },
  {
    "path": "tests/views/shared.blade.php",
    "content": "@shared\n"
  },
  {
    "path": "tests/views/shared_custom.blade.php",
    "content": "@shared_custom\n"
  }
]