<?php

namespace MightyPork\Providers;

use Blade;
use Illuminate\Support\ServiceProvider;

class BladeExtensionsProvider extends ServiceProvider
{
	/**
	 * Parse argument of a blade directive
	 *
	 * @param string $x argument received by a blade directive
	 * @return array the arguments (strings without quotes)
	 */
	private static function parseBladeArgs($x)
	{
		// strip wrapping parens
		return array_map('trim', str_getcsv($x));
	}


	/**
	 * Add blade directives
	 *
	 * @return void
	 */
	public function boot()
	{
		// @faker(text, 100)
		Blade::directive('faker', function ($x) {
			$args = self::parseBladeArgs($x);

			$method = $args[0];
			$params = count($args) > 1 ? $args[1] : '';

			return "<?= e(app()->make('\\Faker\\Generator')->$method($params)) ?>";
		});

		// csrf token for forms
		Blade::directive('formCsrf', function () {
			return '<?= csrf_field() ?>';
		});

		// json encode
		Blade::directive('json', function ($x) {
			if (config('app.pretty_json')) {
				return "<?= json_encode(($x), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES) ?>";
			} else {
				return "<?= json_encode(($x), JSON_UNESCAPED_SLASHES) ?>";
			}
		});

		// json encode, escaped
		Blade::directive('jsone', function ($x) {
			if (config('app.pretty_json')) {
				return "<?= e(json_encode(($x), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES)) ?>";
			} else {
				return "<?= e(json_encode(($x), JSON_UNESCAPED_SLASHES)) ?>";
			}
		});

		// selected if cond true
		Blade::directive('selected', function ($x) {
			return "<?= ($x) ? 'selected' : '' ?>";
		});

		// checked if cond true
		Blade::directive('checked', function ($x) {
			return "<?= ($x) ? 'checked' : '' ?>";
		});

		Blade::if('admin', function () {
			return \Auth::user()->isAdmin();
		});

		Blade::if('set', function ($x) {
			return config($x) != '';
		});
	}

	/**
	 * Register any application services.
	 *
	 * @return void
	 */
	public function register()
	{
		//
	}
}