Repository: coderello/laravel-shared-data
Branch: 4.0
Commit: 5d5cc6e81581
Files: 23
Total size: 29.3 KB
Directory structure:
gitextract_3gqhbw41/
├── .gitattributes
├── .github/
│ └── workflows/
│ ├── run-php-cs-fixer.yml
│ └── run-tests.yml
├── .gitignore
├── .php_cs
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── composer.json
├── config/
│ └── shared-data.php
├── docs/
│ ├── contributing.md
│ ├── installation.md
│ ├── javascript-helper.md
│ └── sharing-data.md
├── phpunit.xml.dist
├── src/
│ ├── Facades/
│ │ └── SharedData.php
│ ├── Providers/
│ │ └── SharedDataServiceProvider.php
│ ├── SharedData.php
│ └── helpers.php
└── tests/
├── AbstractTestCase.php
├── SharedDataTest.php
└── views/
├── shared.blade.php
└── shared_custom.blade.php
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
/.gitattributes export-ignore
/.gitignore export-ignore
/.styleci.yml export-ignore
/phpunit.xml.dist export-ignore
/tests export-ignore
/.travis.yml export-ignore
================================================
FILE: .github/workflows/run-php-cs-fixer.yml
================================================
name: Fix PHP Code Style
on:
workflow_dispatch:
push:
paths:
- '**.php'
jobs:
fix-php-code-style:
name: Fix PHP Code Style
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 2
token: ${{ secrets.GITHUB_TOKEN }}
- name: Run PHP CS Fixer
uses: docker://oskarstark/php-cs-fixer-ga:2.18.6
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: Fix Backend Code Style
skip_fetch: true
================================================
FILE: .github/workflows/run-tests.yml
================================================
name: Run Tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
php: [8.1, 8.0]
laravel: [9.*]
dependency-version: [prefer-lowest, prefer-stable]
include:
- laravel: 9.*
testbench: 7.*
name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }}
steps:
- name: Checkout code
uses: actions/checkout@v1
- name: Cache dependencies
uses: actions/cache@v1
with:
path: ~/.composer/cache/files
key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring
- name: Install dependencies
run: |
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update
composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
- name: Execute tests
run: vendor/bin/phpunit
================================================
FILE: .gitignore
================================================
.idea
vendor
composer.lock
/phpunit.xml
.phpunit.result.cache
.php_cs.cache
================================================
FILE: .php_cs
================================================
<?php
$finder = Symfony\Component\Finder\Finder::create()
->notPath('spark')
->notPath('bootstrap')
->notPath('storage')
->notPath('vendor')
->in(__DIR__)
->name('*.php')
->name('_ide_helper')
->notName('*.blade.php')
->ignoreDotFiles(true)
->ignoreVCS(true);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => ['sortAlgorithm' => 'alpha'],
'no_unused_imports' => true,
])
->setFinder($finder);
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
Contributions are **welcome** and will be fully **credited**.
Please read and understand the contribution guide before creating an issue or pull request.
## Requirements
If the project maintainer has any additional requirements, you will find them listed here.
- **[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).
- **Add tests!** Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour.** Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle.** We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
- **Create feature branches.** Don't ask us to pull from your master branch.
- **One pull request per feature.** If you want to do more than one thing, send multiple pull requests.
- **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.
**Happy coding!**
================================================
FILE: LICENSE.md
================================================
MIT License
Copyright (c) 2018 Coderello
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# Laravel Shared Data
## ✨ Introduction
**Laravel Shared Data** provides an easy way to share the data from your backend to the JavaScript.
## 🚀 Quick start
- Install the package:
```bash
composer require coderello/laravel-shared-data
```
- Include the `@shared` directive into your blade layout before all scripts.
- Share the data from within Laravel:
```bash
share(['user' => $user, 'title' => $title]);
```
- Access the data from the JavaScript directly:
```bash
const user = window.sharedData.user;
const title = window.sharedData.title;
```
- Or using the built-it global helper:
```bash
const user = shared('user');
const title = shared('title');
```
## 📖 License
**Laravel Shared Data** is open-sourced software licensed under the [MIT license](LICENSE.md).
================================================
FILE: composer.json
================================================
{
"name": "coderello/laravel-shared-data",
"description": "Package for sharing data from Laravel to JavaScript.",
"type": "library",
"license": "MIT",
"require": {
"php": "^8.0",
"ext-json": "*",
"illuminate/support": "^9.0"
},
"require-dev": {
"orchestra/testbench": "^7.0"
},
"autoload": {
"psr-4": {
"Coderello\\SharedData\\": "src/"
},
"files": [
"src/helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"Coderello\\SharedData\\Tests\\": "tests/"
}
},
"scripts": {
"test": "./vendor/bin/phpunit --colors=always"
},
"extra": {
"laravel": {
"providers": [
"Coderello\\SharedData\\Providers\\SharedDataServiceProvider"
]
}
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
}
================================================
FILE: config/shared-data.php
================================================
<?php
/**
* @see https://github.com/coderello/laravel-shared-data
*/
return [
/*
* JavaScript namespace.
*
* By default the namespace is equal to 'sharedData'.
*
* It means that the shared data will be accessible from `window.sharedData`
*/
'js_namespace' => 'sharedData',
/*
* The settings for the JavaScript helper function that allows
* retrieving the shared data on the front-end side easily.
*
* Example: `shared('user.email')`
*/
'js_helper' => [
/*
* Determines whether the JavaScript helper should be included
* alongside with the shared data.
*/
'enabled' => true,
/*
* The function name for the JavaScript helper.
*/
'name' => 'shared',
],
/*
* The settings for the Blade directive.
*/
'blade_directive' => [
/*
* Blade directive name.
*
* By default the Blade directive named 'shared'.
*
* It means that the shared data rendering will be available in view files via `@shared`.
*/
'name' => 'shared',
],
];
================================================
FILE: docs/contributing.md
================================================
---
title: Contribution Guide
section: Contributing
weight: 100
featherIcon: github
---
Contributions are **welcome** and will be fully **credited**.
Please read and understand the contribution guide before creating an issue or pull request.
## Requirements
If the project maintainer has any additional requirements, you will find them listed here.
- **[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).
- **Add tests!** Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour.** Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle.** We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
- **Create feature branches.** Don't ask us to pull from your master branch.
- **One pull request per feature.** If you want to do more than one thing, send multiple pull requests.
- **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.
**Happy coding!**
================================================
FILE: docs/installation.md
================================================
---
title: Installation
section: Getting Started
weight: 5000
featherIcon: download
---
You can install this package via composer using this command:
```bash
composer require coderello/laravel-shared-data
```
After the installation you need to include `@shared` directive into your blade layout before all `<script>` tags.

## Publishing the config
To publish the config file to `config/shared-data.php` run:
```bash
php artisan vendor:publish --provider="Coderello\SharedData\Providers\SharedDataServiceProvider" --tag="config"
```
================================================
FILE: docs/javascript-helper.md
================================================
---
title: JavaScript helper
section: Getting Started
weight: 800
featherIcon: coffee
---
TBD
================================================
FILE: docs/sharing-data.md
================================================
---
title: Sharing data
section: Getting Started
weight: 900
featherIcon: package
---
You can share any data you want from any part or your application (middleware, controller, service provider etc.)
```php
use Coderello\SharedData\Facades\SharedData;
// using the facade
SharedData::put([
'user' => auth()->user(),
'post' => Post::first(),
'app' => [
'name' => config('app.name'),
'environment' => config('app.env'),
],
]);
// using the helper
share([
'user' => auth()->user(),
'post' => Post::first(),
'app' => [
'name' => config('app.name'),
'environment' => config('app.env'),
],
]);
```
And get this data on the frontend side directly from `window.sharedData` (use can modify the namespace in the config file) like so:
```js
const user = window.sharedData.user;
```
Or using the global built-in helper:
```js
const user = shared('user');
```
> You can get more info on the global built-in helper on the [JavaScript helper]({{base}}/{{version}}/javascript-helper) page.

================================================
FILE: phpunit.xml.dist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
beStrictAboutTestsThatDoNotTestAnything="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<testsuites>
<testsuite name="Laravel Shared Data Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src/</directory>
</whitelist>
</filter>
</phpunit>
================================================
FILE: src/Facades/SharedData.php
================================================
<?php
namespace Coderello\SharedData\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @see \Coderello\SharedData\SharedData
*
* @method static \Coderello\SharedData\SharedData put(mixed $key, mixed $value = null)
* @method static mixed get(mixed $key = null)
* @method static string toJson(int $options = 0)
* @method static string render()
*/
class SharedData extends Facade
{
/**
* {@inheritdoc}
*/
protected static function getFacadeAccessor()
{
return \Coderello\SharedData\SharedData::class;
}
}
================================================
FILE: src/Providers/SharedDataServiceProvider.php
================================================
<?php
namespace Coderello\SharedData\Providers;
use Coderello\SharedData\SharedData;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;
class SharedDataServiceProvider extends ServiceProvider implements DeferrableProvider
{
/**
* Bootstrap shared data service.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../../config/shared-data.php' => config_path('shared-data.php'),
], 'shared-data-config');
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../../config/shared-data.php',
'shared-data'
);
$this->app->singleton(SharedData::class, function () {
return new SharedData($this->app['config']['shared-data']);
});
$this->app->extend('blade.compiler', function (BladeCompiler $bladeCompiler) {
$bladeCompiler->directive($this->app['config']['shared-data.blade_directive.name'] ?? 'shared', function () {
return '<?php echo app(\\'.SharedData::class.'::class)->render(); ?>';
});
return $bladeCompiler;
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [
SharedData::class,
'blade.compiler'
];
}
}
================================================
FILE: src/SharedData.php
================================================
<?php
namespace Coderello\SharedData;
use ArrayAccess;
use Closure;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Arr;
use InvalidArgumentException;
use JsonSerializable;
class SharedData implements Renderable, Jsonable, Arrayable, JsonSerializable, ArrayAccess
{
/** @var array */
private $data = [];
/** @var string */
private $jsNamespace = 'sharedData';
/** @var bool */
private $jsHelperEnabled = true;
/** @var string */
private $jsHelperName = 'shared';
/** @var Closure[]|array */
private $delayedClosures = [];
/** @var Closure[]|array */
private $delayedClosuresWithKeys = [];
public function __construct(array $config = [])
{
$this->hydrateConfig($config);
}
private function hydrateConfig(array $config)
{
if (Arr::has($config, 'js_namespace')) {
$this->setJsNamespace(Arr::get($config, 'js_namespace'));
}
if (Arr::has($config, 'js_helper.enabled')) {
$this->setJsHelperEnabled(Arr::get($config, 'js_helper.enabled'));
}
if (Arr::has($config, 'js_helper.name')) {
$this->setJsHelperName(Arr::get($config, 'js_helper.name'));
}
}
private function unpackDelayedClosures(): self
{
foreach ($this->delayedClosures as $delayedClosure) {
$this->put($delayedClosure());
}
$this->delayedClosures = [];
foreach ($this->delayedClosuresWithKeys as $key => $delayedClosure) {
$this->put($key, $delayedClosure());
}
$this->delayedClosuresWithKeys = [];
return $this;
}
public function put($key, $value = null)
{
if (is_scalar($key) && $value instanceof Closure) {
$this->delayedClosuresWithKeys[$key] = $value;
} elseif (is_scalar($key)) {
Arr::set($this->data, $key, $value);
} elseif (is_iterable($key)) {
foreach ($key as $nestedKey => $nestedValue) {
$this->put($nestedKey, $nestedValue);
}
} elseif ($key instanceof JsonSerializable) {
$this->put($key->jsonSerialize());
} elseif ($key instanceof Arrayable) {
$this->put($key->toArray());
} elseif ($key instanceof Closure) {
$this->delayedClosures[] = $key;
} elseif (is_object($key)) {
$this->put(get_object_vars($key));
} else {
throw new InvalidArgumentException('Key type ['.gettype($key).'] is not supported.');
}
return $this;
}
public function get($key = null)
{
$this->unpackDelayedClosures();
if (is_null($key)) {
return $this->data;
}
return Arr::get($this->data, $key);
}
public function forget($key = null): self
{
$this->unpackDelayedClosures();
if (is_null($key)) {
$this->data = [];
} else {
Arr::forget($this->data, $key);
}
return $this;
}
public function getJsNamespace(): string
{
return $this->jsNamespace;
}
public function setJsNamespace(string $jsNamespace): self
{
$this->jsNamespace = $jsNamespace;
return $this;
}
public function getJsHelperEnabled(): bool
{
return $this->jsHelperEnabled;
}
public function setJsHelperEnabled(bool $jsHelperEnabled): self
{
$this->jsHelperEnabled = $jsHelperEnabled;
return $this;
}
public function getJsHelperName(): string
{
return $this->jsHelperName;
}
public function setJsHelperName(string $jsHelperName): self
{
$this->jsHelperName = $jsHelperName;
return $this;
}
public function toJson($options = 0): string
{
return json_encode($this->get(), $options);
}
public function render(array $options = []): string
{
$attributes = $options['attributes'] ?? [];
$attributeStrings = [];
foreach ($attributes as $attributeName => $attributeValue) {
$attributeStrings[] = $attributeName.'="'.htmlentities($attributeValue, ENT_QUOTES, 'UTF-8', false).'"';
}
return (count($attributeStrings) === 0 ? '<script>' : '<script '.implode(' ', $attributeStrings).'>')
.'window["'.$this->getJsNamespace().'"]='.$this->toJson().';'
.'window["sharedDataNamespace"]="'.$this->getJsNamespace().'";'
.($this->getJsHelperEnabled() ? $this->getJsHelper().';' : '')
.'</script>';
}
public function getJsHelper(): string
{
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)}';
}
public function __toString(): string
{
return $this->render();
}
public function toArray(): array
{
return $this->get();
}
public function jsonSerialize(): array
{
return $this->get();
}
public function offsetExists($offset): bool
{
return Arr::has($this->data, $offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value): void
{
$this->put($offset, $value);
}
public function offsetUnset($offset): void
{
$this->forget($offset);
}
}
================================================
FILE: src/helpers.php
================================================
<?php
if (! function_exists('shared')) {
/**
* @return \Coderello\SharedData\SharedData
*/
function shared()
{
return app(\Coderello\SharedData\SharedData::class);
}
}
if (! function_exists('share')) {
/**
* @param array $args
* @return \Coderello\SharedData\SharedData
*/
function share(...$args)
{
return app(\Coderello\SharedData\SharedData::class)->put(...$args);
}
}
================================================
FILE: tests/AbstractTestCase.php
================================================
<?php
namespace Coderello\SharedData\Tests;
use Coderello\SharedData\Providers\SharedDataServiceProvider;
use Orchestra\Testbench\TestCase;
abstract class AbstractTestCase extends TestCase
{
protected function setUp(): void
{
parent::setUp();
view()->addLocation(__DIR__.'/views');
}
protected function getPackageProviders($app)
{
return [
SharedDataServiceProvider::class,
];
}
}
================================================
FILE: tests/SharedDataTest.php
================================================
<?php
namespace Coderello\SharedData\Tests;
use Coderello\SharedData\SharedData;
use Illuminate\Contracts\Support\Arrayable;
use JsonSerializable;
use stdClass;
class SharedDataTest extends AbstractTestCase
{
/** @var SharedData|null */
protected $sharedData;
/** @var mixed|null */
protected $lazy;
protected function setUp(): void
{
parent::setUp();
$this->sharedData = new SharedData;
$this->lazy = null;
}
public function testPut()
{
// scalar
$this->sharedData->put('foo', 'bar');
$this->assertSame('bar', $this->sharedData->get('foo'));
// iterable
$this->sharedData->put([
'scalar' => 'scalar-value',
'array' => ['nested' => 'value'],
]);
$this->assertSame('scalar-value', $this->sharedData->get('scalar'));
$this->assertSame(['nested' => 'value'], $this->sharedData->get('array'));
// JsonSerializable
$jsonSerializable = new class implements JsonSerializable {
public function jsonSerialize()
{
return [
'json-serializable-key' => 'json-serializable-value',
];
}
};
$this->sharedData->put($jsonSerializable);
$this->assertSame('json-serializable-value', $this->sharedData->get('json-serializable-key'));
// Arrayable
$arrayable = new class implements Arrayable {
public function toArray()
{
return [
'arrayable-key' => 'arrayable-value',
];
}
};
$this->sharedData->put($arrayable);
$this->assertSame('arrayable-value', $this->sharedData->get('arrayable-key'));
// Closure (lazy)
$this->lazy = 'foo';
$this->sharedData->put(function () {
return [
'lazy' => $this->lazy,
];
});
$this->lazy = 'bar';
$this->assertSame('bar', $this->sharedData->get('lazy'));
// Closure (lazy) with key
$this->lazy = 'foo';
$this->sharedData->put('lazy-with-key', function () {
return $this->lazy;
});
$this->lazy = 'bar';
$this->assertSame('bar', $this->sharedData->get('lazy-with-key'));
// object
$object = new stdClass;
$object->objectScalar = 'object-scalar';
$object->objectArray = ['nested' => 'object-scalar'];
$this->sharedData->put($object);
$this->assertSame('object-scalar', $this->sharedData->get('objectScalar'));
$this->assertSame(['nested' => 'object-scalar'], $this->sharedData->get('objectArray'));
}
public function testGet()
{
$values = [
'scalar' => 'scalar-value',
'array' => ['nested' => 'value'],
];
$this->sharedData->put($values);
$this->assertSame('scalar-value', $this->sharedData->get('scalar'));
$this->assertSame($values, $this->sharedData->get());
}
public function testToJson()
{
$this->sharedData->put([
'scalar' => 'scalar-value',
'array' => ['nested' => 'value'],
]);
$json = $this->sharedData->toJson();
$expectedJson = '{"scalar":"scalar-value","array":{"nested":"value"}}';
$this->assertSame($expectedJson, $json);
}
public function testRender()
{
$this->sharedData->put([
'scalar' => 'scalar-value',
'array' => ['nested' => 'value'],
]);
$this->sharedData->setJsNamespace('customShareDataNamespace');
$this->sharedData->setJsHelperName('customSharedFunctionName');
$this->sharedData->setJsHelperEnabled(true);
$html = $this->sharedData->render();
$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>';
$this->assertSame($expectedHtml, $html);
}
public function testRenderWithAttributes()
{
$this->sharedData->put([
'scalar' => 'scalar-value',
'array' => ['nested' => 'value'],
]);
$this->sharedData->setJsNamespace('customShareDataNamespace');
$this->sharedData->setJsHelperName('customSharedFunctionName');
$this->sharedData->setJsHelperEnabled(true);
$html = $this->sharedData->render(['attributes' => ['nonce' => 'HELLOWORLD">', 'data-hello' => 'world']]);
$expectedHtml = '<script nonce="HELLOWORLD">" 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>';
$this->assertSame($expectedHtml, $html);
}
public function testToString()
{
$this->sharedData->put('foo', 'bar');
$this->assertSame($this->sharedData->render(), (string) $this->sharedData);
}
public function testJsNamespace()
{
$this->assertSame('sharedData', $this->sharedData->getJsNamespace());
$this->sharedData->setJsNamespace('foo');
$this->assertSame('foo', $this->sharedData->getJsNamespace());
}
public function testJsHelperName()
{
$this->assertSame('shared', $this->sharedData->getJsHelperName());
$this->sharedData->setJsHelperName('customShared');
$this->assertSame('customShared', $this->sharedData->getJsHelperName());
}
public function testJsHelperEnabled()
{
$this->assertSame(true, $this->sharedData->getJsHelperEnabled());
$this->sharedData->setJsHelperEnabled(false);
$this->assertSame(false, $this->sharedData->getJsHelperEnabled());
}
public function testJsHelper()
{
$this->sharedData->setJsHelperName('customSharedFunctionName');
$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());
}
public function testToArray()
{
$this->sharedData->put('foo', ['bar' => 'baz']);
$this->assertSame(['foo' => ['bar' => 'baz']], $this->sharedData->toArray());
}
public function testJsonSerialize()
{
$this->sharedData->put('foo', ['bar' => 'baz']);
$this->assertSame(['foo' => ['bar' => 'baz']], $this->sharedData->jsonSerialize());
}
public function testOffsetExists()
{
$this->sharedData->put('foo.baz', 'bar');
$this->assertTrue(isset($this->sharedData['foo.baz']));
$this->assertFalse(isset($this->sharedData['baz.foo']));
}
public function testOffsetGet()
{
$this->sharedData->put('foo.bar', 'baz');
$this->assertSame('baz', $this->sharedData['foo.bar']);
}
public function testOffsetSet()
{
$this->sharedData['foo.bar'] = 'baz';
$this->assertSame(
[
'foo' => [
'bar' => 'baz',
],
],
$this->sharedData->get()
);
}
public function testOffsetUnset()
{
$this->sharedData->put([
'foo' => [
'bar' => 'baz',
'baz' => 'bar',
],
]);
unset($this->sharedData['foo.baz']);
$this->assertSame(
[
'foo' => [
'bar' => 'baz',
],
],
$this->sharedData->get()
);
}
public function testForget()
{
$this->sharedData->put([
'foo' => [
'bar' => 'baz',
'baz' => 'bar',
],
]);
$this->sharedData->forget('foo.baz');
$this->assertSame(
[
'foo' => [
'bar' => 'baz',
],
],
$this->sharedData->get()
);
$this->sharedData->forget();
$this->assertSame([], $this->sharedData->get());
}
public function testBladeDirective()
{
$this->assertEquals(
shared()->render(),
view('shared')->render()
);
}
/**
* @depends testBladeDirective
*/
public function testBladeDirectiveWithCustomName()
{
$this->app['config']['shared-data.blade_directive.name'] = 'shared_custom';
$this->assertEquals(
shared()->render(),
view('shared_custom')->render()
);
}
}
================================================
FILE: tests/views/shared.blade.php
================================================
@shared
================================================
FILE: tests/views/shared_custom.blade.php
================================================
@shared_custom
gitextract_3gqhbw41/
├── .gitattributes
├── .github/
│ └── workflows/
│ ├── run-php-cs-fixer.yml
│ └── run-tests.yml
├── .gitignore
├── .php_cs
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── composer.json
├── config/
│ └── shared-data.php
├── docs/
│ ├── contributing.md
│ ├── installation.md
│ ├── javascript-helper.md
│ └── sharing-data.md
├── phpunit.xml.dist
├── src/
│ ├── Facades/
│ │ └── SharedData.php
│ ├── Providers/
│ │ └── SharedDataServiceProvider.php
│ ├── SharedData.php
│ └── helpers.php
└── tests/
├── AbstractTestCase.php
├── SharedDataTest.php
└── views/
├── shared.blade.php
└── shared_custom.blade.php
SYMBOL INDEX (55 symbols across 6 files)
FILE: src/Facades/SharedData.php
class SharedData (line 15) | class SharedData extends Facade
method getFacadeAccessor (line 20) | protected static function getFacadeAccessor()
FILE: src/Providers/SharedDataServiceProvider.php
class SharedDataServiceProvider (line 10) | class SharedDataServiceProvider extends ServiceProvider implements Defer...
method boot (line 17) | public function boot()
method register (line 29) | public function register()
method provides (line 54) | public function provides()
FILE: src/SharedData.php
class SharedData (line 14) | class SharedData implements Renderable, Jsonable, Arrayable, JsonSeriali...
method __construct (line 34) | public function __construct(array $config = [])
method hydrateConfig (line 39) | private function hydrateConfig(array $config)
method unpackDelayedClosures (line 54) | private function unpackDelayedClosures(): self
method put (line 71) | public function put($key, $value = null)
method get (line 96) | public function get($key = null)
method forget (line 107) | public function forget($key = null): self
method getJsNamespace (line 120) | public function getJsNamespace(): string
method setJsNamespace (line 125) | public function setJsNamespace(string $jsNamespace): self
method getJsHelperEnabled (line 132) | public function getJsHelperEnabled(): bool
method setJsHelperEnabled (line 137) | public function setJsHelperEnabled(bool $jsHelperEnabled): self
method getJsHelperName (line 144) | public function getJsHelperName(): string
method setJsHelperName (line 149) | public function setJsHelperName(string $jsHelperName): self
method toJson (line 156) | public function toJson($options = 0): string
method render (line 161) | public function render(array $options = []): string
method getJsHelper (line 178) | public function getJsHelper(): string
method __toString (line 183) | public function __toString(): string
method toArray (line 188) | public function toArray(): array
method jsonSerialize (line 193) | public function jsonSerialize(): array
method offsetExists (line 198) | public function offsetExists($offset): bool
method offsetGet (line 203) | public function offsetGet($offset)
method offsetSet (line 208) | public function offsetSet($offset, $value): void
method offsetUnset (line 213) | public function offsetUnset($offset): void
FILE: src/helpers.php
function shared (line 7) | function shared()
function share (line 18) | function share(...$args)
FILE: tests/AbstractTestCase.php
class AbstractTestCase (line 8) | abstract class AbstractTestCase extends TestCase
method setUp (line 10) | protected function setUp(): void
method getPackageProviders (line 17) | protected function getPackageProviders($app)
FILE: tests/SharedDataTest.php
class SharedDataTest (line 10) | class SharedDataTest extends AbstractTestCase
method setUp (line 18) | protected function setUp(): void
method testPut (line 27) | public function testPut()
method testGet (line 117) | public function testGet()
method testToJson (line 131) | public function testToJson()
method testRender (line 145) | public function testRender()
method testRenderWithAttributes (line 165) | public function testRenderWithAttributes()
method testToString (line 185) | public function testToString()
method testJsNamespace (line 192) | public function testJsNamespace()
method testJsHelperName (line 201) | public function testJsHelperName()
method testJsHelperEnabled (line 210) | public function testJsHelperEnabled()
method testJsHelper (line 219) | public function testJsHelper()
method testToArray (line 226) | public function testToArray()
method testJsonSerialize (line 233) | public function testJsonSerialize()
method testOffsetExists (line 240) | public function testOffsetExists()
method testOffsetGet (line 249) | public function testOffsetGet()
method testOffsetSet (line 256) | public function testOffsetSet()
method testOffsetUnset (line 270) | public function testOffsetUnset()
method testForget (line 291) | public function testForget()
method testBladeDirective (line 316) | public function testBladeDirective()
method testBladeDirectiveWithCustomName (line 327) | public function testBladeDirectiveWithCustomName()
Condensed preview — 23 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (33K chars).
[
{
"path": ".gitattributes",
"chars": 163,
"preview": "/.gitattributes export-ignore\n/.gitignore export-ignore\n/.styleci.yml export-ignore\n/phpunit.xml.dist export-ignore\n/tes"
},
{
"path": ".github/workflows/run-php-cs-fixer.yml",
"chars": 564,
"preview": "name: Fix PHP Code Style\n\non:\n workflow_dispatch:\n push:\n paths:\n - '**.php'\n\njobs:\n fix-php-code-style:\n "
},
{
"path": ".github/workflows/run-tests.yml",
"chars": 1163,
"preview": "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."
},
{
"path": ".gitignore",
"chars": 75,
"preview": ".idea\nvendor\ncomposer.lock\n/phpunit.xml\n.phpunit.result.cache\n.php_cs.cache"
},
{
"path": ".php_cs",
"chars": 557,
"preview": "<?php\n\n$finder = Symfony\\Component\\Finder\\Finder::create()\n ->notPath('spark')\n ->notPath('bootstrap')\n ->notPa"
},
{
"path": "CONTRIBUTING.md",
"chars": 1355,
"preview": "# Contributing\n\nContributions are **welcome** and will be fully **credited**.\n\nPlease read and understand the contributi"
},
{
"path": "LICENSE.md",
"chars": 1066,
"preview": "MIT License\n\nCopyright (c) 2018 Coderello\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n"
},
{
"path": "README.md",
"chars": 850,
"preview": "# Laravel Shared Data\n\n## ✨ Introduction\n\n**Laravel Shared Data** provides an easy way to share the data from your backe"
},
{
"path": "composer.json",
"chars": 979,
"preview": "{\n \"name\": \"coderello/laravel-shared-data\",\n \"description\": \"Package for sharing data from Laravel to JavaScript.\""
},
{
"path": "config/shared-data.php",
"chars": 1168,
"preview": "<?php\n/**\n * @see https://github.com/coderello/laravel-shared-data\n */\n\nreturn [\n\n /*\n * JavaScript namespace.\n "
},
{
"path": "docs/contributing.md",
"chars": 1428,
"preview": "---\ntitle: Contribution Guide\nsection: Contributing\nweight: 100\nfeatherIcon: github\n---\n\nContributions are **welcome** a"
},
{
"path": "docs/installation.md",
"chars": 594,
"preview": "---\ntitle: Installation\nsection: Getting Started\nweight: 5000\nfeatherIcon: download\n---\n\nYou can install this package vi"
},
{
"path": "docs/javascript-helper.md",
"chars": 94,
"preview": "---\ntitle: JavaScript helper\nsection: Getting Started\nweight: 800\nfeatherIcon: coffee\n---\n\nTBD"
},
{
"path": "docs/sharing-data.md",
"chars": 1117,
"preview": "---\ntitle: Sharing data\nsection: Getting Started\nweight: 900\nfeatherIcon: package\n---\n\nYou can share any data you want f"
},
{
"path": "phpunit.xml.dist",
"chars": 775,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit backupGlobals=\"false\"\n backupStaticAttributes=\"false\"\n b"
},
{
"path": "src/Facades/SharedData.php",
"chars": 550,
"preview": "<?php\n\nnamespace Coderello\\SharedData\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\n/**\n * @see \\Coderello\\SharedDat"
},
{
"path": "src/Providers/SharedDataServiceProvider.php",
"chars": 1570,
"preview": "<?php\n\nnamespace Coderello\\SharedData\\Providers;\n\nuse Coderello\\SharedData\\SharedData;\nuse Illuminate\\Contracts\\Support\\"
},
{
"path": "src/SharedData.php",
"chars": 5683,
"preview": "<?php\n\nnamespace Coderello\\SharedData;\n\nuse ArrayAccess;\nuse Closure;\nuse Illuminate\\Contracts\\Support\\Arrayable;\nuse Il"
},
{
"path": "src/helpers.php",
"chars": 447,
"preview": "<?php\n\nif (! function_exists('shared')) {\n /**\n * @return \\Coderello\\SharedData\\SharedData\n */\n function s"
},
{
"path": "tests/AbstractTestCase.php",
"chars": 454,
"preview": "<?php\n\nnamespace Coderello\\SharedData\\Tests;\n\nuse Coderello\\SharedData\\Providers\\SharedDataServiceProvider;\nuse Orchestr"
},
{
"path": "tests/SharedDataTest.php",
"chars": 9342,
"preview": "<?php\n\nnamespace Coderello\\SharedData\\Tests;\n\nuse Coderello\\SharedData\\SharedData;\nuse Illuminate\\Contracts\\Support\\Arra"
},
{
"path": "tests/views/shared.blade.php",
"chars": 8,
"preview": "@shared\n"
},
{
"path": "tests/views/shared_custom.blade.php",
"chars": 15,
"preview": "@shared_custom\n"
}
]
About this extraction
This page contains the full source code of the coderello/laravel-shared-data GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 23 files (29.3 KB), approximately 7.9k tokens, and a symbol index with 55 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.