protected function resolveTransformer($transformable)
    {
        if (is_object($transformable) && key_exists(get_class($transformable), $this->bindings)) {
            return $this->bindings[get_class($transformable)];
        }

        if ($transformable instanceof Transformable) {
            return $transformable->transformer();
        }

        return $this->resolve($this->fallback);
    }

protected function resolveTransformer ( $ transformable ) { if ( is_object ( $ transformable ) && key_exists ( get_class ( $ transformable ) , $ this -> bindings ) ) { return $ this -> bindings [ get_class ( $ transformable ) ] ; } if ( $ transformable instanceof Transformable ) { return $ transformable -> transformer ( ) ; } return $ this -> resolve ( $ this -> fallback ) ; }

Resolve a transformer from the transformable element.

@param  mixed $transformable
@return \Flugg\Responder\Contracts\Transformable|callable

Resolve a transformer from the transformable element .


protected function registerLaravelBindings()
    {
        $this->app->singleton(ResponseFactoryContract::class, function ($app) {
            return $this->decorateResponseFactory($app->make(LaravelResponseFactory::class));
        });
    }

protected function registerLaravelBindings ( ) { $ this -> app -> singleton ( ResponseFactoryContract :: class , function ( $ app ) { return $ this -> decorateResponseFactory ( $ app -> make ( LaravelResponseFactory :: class ) ) ; } ) ; }

Register Laravel bindings.

@return void


protected function registerLumenBindings()
    {
        $this->app->singleton(ResponseFactoryContract::class, function ($app) {
            return $this->decorateResponseFactory($app->make(LumenResponseFactory::class));
        });

        $this->app->bind(Translator::class, function ($app) {
            return $app['translator'];
        });
    }

protected function registerLumenBindings ( ) { $ this -> app -> singleton ( ResponseFactoryContract :: class , function ( $ app ) { return $ this -> decorateResponseFactory ( $ app -> make ( LumenResponseFactory :: class ) ) ; } ) ; $ this -> app -> bind ( Translator :: class , function ( $ app ) { return $ app [ 'translator' ] ; } ) ; }


protected function decorateResponseFactory(ResponseFactoryContract $factory): ResponseFactory
    {
        foreach ($this->app->config['responder.decorators'] as $decorator) {
            $factory = new $decorator($factory);
        };

        return $factory;
    }

protected function decorateResponseFactory ( ResponseFactoryContract $ factory ) : ResponseFactory { foreach ( $ this -> app -> config [ 'responder.decorators' ] as $ decorator ) { $ factory = new $ decorator ( $ factory ) ; } ; return $ factory ; }

Decorate response factories.

@param  \Flugg\Responder\Contracts\ResponseFactory $factory
@return \Flugg\Responder\Contracts\ResponseFactory


protected function registerSerializerBindings()
    {
        $this->app->bind(ErrorSerializerContract::class, function ($app) {
            return $app->make($app->config['responder.serializers.error']);
        });

        $this->app->bind(SerializerAbstract::class, function ($app) {
            return $app->make($app->config['responder.serializers.success']);
        });
    }

protected function registerSerializerBindings ( ) { $ this -> app -> bind ( ErrorSerializerContract :: class , function ( $ app ) { return $ app -> make ( $ app -> config [ 'responder.serializers.error' ] ) ; } ) ; $ this -> app -> bind ( SerializerAbstract :: class , function ( $ app ) { return $ app -> make ( $ app -> config [ 'responder.serializers.success' ] ) ; } ) ; }

Register serializer bindings.

@return void


protected function registerErrorBindings()
    {
        $this->app->singleton(ErrorMessageResolverContract::class, function ($app) {
            return $app->make(ErrorMessageResolver::class);
        });

        $this->app->singleton(ErrorFactoryContract::class, function ($app) {
            return $app->make(ErrorFactory::class);
        });

        $this->app->bind(ErrorResponseBuilder::class, function ($app) {
            return (new ErrorResponseBuilder($app->make(ResponseFactoryContract::class), $app->make(ErrorFactoryContract::class)))->serializer($app->make(ErrorSerializerContract::class));
        });
    }

protected function registerErrorBindings ( ) { $ this -> app -> singleton ( ErrorMessageResolverContract :: class , function ( $ app ) { return $ app -> make ( ErrorMessageResolver :: class ) ; } ) ; $ this -> app -> singleton ( ErrorFactoryContract :: class , function ( $ app ) { return $ app -> make ( ErrorFactory :: class ) ; } ) ; $ this -> app -> bind ( ErrorResponseBuilder :: class , function ( $ app ) { return ( new ErrorResponseBuilder ( $ app -> make ( ResponseFactoryContract :: class ) , $ app -> make ( ErrorFactoryContract :: class ) ) ) -> serializer ( $ app -> make ( ErrorSerializerContract :: class ) ) ; } ) ; }


protected function registerFractalBindings()
    {
        $this->app->bind(Manager::class, function ($app) {
            return (new Manager)->setRecursionLimit($app->config['responder.recursion_limit']);
        });
    }

protected function registerFractalBindings ( ) { $ this -> app -> bind ( Manager :: class , function ( $ app ) { return ( new Manager ) -> setRecursionLimit ( $ app -> config [ 'responder.recursion_limit' ] ) ; } ) ; }

Register Fractal bindings.

@return void


protected function registerTransformerBindings()
    {
        $this->app->singleton(TransformerResolverContract::class, function ($app) {
            return new TransformerResolver($app, $app->config['responder.fallback_transformer']);
        });

        BaseTransformer::containerResolver(function () {
            return $this->app->make(Container::class);
        });
    }

protected function registerTransformerBindings ( ) { $ this -> app -> singleton ( TransformerResolverContract :: class , function ( $ app ) { return new TransformerResolver ( $ app , $ app -> config [ 'responder.fallback_transformer' ] ) ; } ) ; BaseTransformer :: containerResolver ( function ( ) { return $ this -> app -> make ( Container :: class ) ; } ) ; }

Register transformer bindings.

@return void


protected function registerTransformationBindings()
    {
        $this->app->bind(TransformFactoryContract::class, function ($app) {
            return $app->make(FractalTransformFactory::class);
        });

        $this->app->bind(TransformBuilder::class, function ($app) {
            $request = $this->app->make(Request::class);
            $relations = $request->input($this->app->config['responder.load_relations_parameter'], []);
            $fieldsets = $request->input($app->config['responder.filter_fields_parameter'], []);

            return (new TransformBuilder($app->make(ResourceFactoryContract::class), $app->make(TransformFactoryContract::class), $app->make(PaginatorFactoryContract::class)))->serializer($app->make(SerializerAbstract::class))
                ->with(is_string($relations) ? explode(',', $relations) : $relations)
                ->only($fieldsets);
        });
    }

protected function registerTransformationBindings ( ) { $ this -> app -> bind ( TransformFactoryContract :: class , function ( $ app ) { return $ app -> make ( FractalTransformFactory :: class ) ; } ) ; $ this -> app -> bind ( TransformBuilder :: class , function ( $ app ) { $ request = $ this -> app -> make ( Request :: class ) ; $ relations = $ request -> input ( $ this -> app -> config [ 'responder.load_relations_parameter' ] , [ ] ) ; $ fieldsets = $ request -> input ( $ app -> config [ 'responder.filter_fields_parameter' ] , [ ] ) ; return ( new TransformBuilder ( $ app -> make ( ResourceFactoryContract :: class ) , $ app -> make ( TransformFactoryContract :: class ) , $ app -> make ( PaginatorFactoryContract :: class ) ) ) -> serializer ( $ app -> make ( SerializerAbstract :: class ) ) -> with ( is_string ( $ relations ) ? explode ( ',' , $ relations ) : $ relations ) -> only ( $ fieldsets ) ; } ) ; }

Register transformation bindings.

@return void


protected function bootLaravelApplication()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__ . '/../config/responder.php' => config_path('responder.php'),
            ], 'config');
            $this->publishes([
                __DIR__ . '/../resources/lang/en/errors.php' => base_path('resources/lang/en/errors.php'),
            ], 'lang');
        }
    }

protected function bootLaravelApplication ( ) { if ( $ this -> app -> runningInConsole ( ) ) { $ this -> publishes ( [ __DIR__ . '/../config/responder.php' => config_path ( 'responder.php' ) , ] , 'config' ) ; $ this -> publishes ( [ __DIR__ . '/../resources/lang/en/errors.php' => base_path ( 'resources/lang/en/errors.php' ) , ] , 'lang' ) ; } }

Bootstrap the Laravel application.

@return void


public function set($data): CursorPaginator
    {
        $this->items = $data instanceof Collection ? $data : collect($data);

        return $this;
    }

public function set ( $ data ) : CursorPaginator { $ this -> items = $ data instanceof Collection ? $ data : collect ( $ data ) ; return $ this ; }

Set the paginator's underlying collection.

@param  \Illuminate\Support\Collection|array|null $data
@return self

Set the paginator s underlying collection .


public function format($errorCode = null, string $message = null, array $data = null): array
    {
        $response = [
            'error' => [
                'code' => $errorCode,
                'message' => $message,
            ],
        ];

        if (is_array($data)) {
            $response['error'] = array_merge($response['error'], $data);
        }

        return $response;
    }

public function format ( $ errorCode = null , string $ message = null , array $ data = null ) : array { $ response = [ 'error' => [ 'code' => $ errorCode , 'message' => $ message , ] , ] ; if ( is_array ( $ data ) ) { $ response [ 'error' ] = array_merge ( $ response [ 'error' ] , $ data ) ; } return $ response ; }

Format the error data.

@param  mixed|null  $errorCode
@param  string|null $message
@param  array|null  $data
@return array


public function relations(array $requested = []): array
    {
        $requested = $this->normalizeRelations($requested);
        $relations = $this->applyQueryConstraints($this->extractRelations($requested));
        $nestedRelations = $this->nestedRelations($requested, $relations, 'relations');

        return array_merge($relations, $nestedRelations);
    }

public function relations ( array $ requested = [ ] ) : array { $ requested = $ this -> normalizeRelations ( $ requested ) ; $ relations = $ this -> applyQueryConstraints ( $ this -> extractRelations ( $ requested ) ) ; $ nestedRelations = $ this -> nestedRelations ( $ requested , $ relations , 'relations' ) ; return array_merge ( $ relations , $ nestedRelations ) ; }

Get a list of whitelisted relations that are requested, including nested relations.

@param  array $requested
@return array

Get a list of whitelisted relations that are requested including nested relations .


public function defaultRelations(array $requested = []): array
    {
        $requested = $this->normalizeRelations($requested);
        $relations = $this->applyQueryConstraints($this->normalizeRelations($this->load));
        $nestedRelations = $this->nestedRelations($relations, array_merge($relations, $requested), 'defaultRelations');

        return array_merge($relations, $nestedRelations);
    }

public function defaultRelations ( array $ requested = [ ] ) : array { $ requested = $ this -> normalizeRelations ( $ requested ) ; $ relations = $ this -> applyQueryConstraints ( $ this -> normalizeRelations ( $ this -> load ) ) ; $ nestedRelations = $ this -> nestedRelations ( $ relations , array_merge ( $ relations , $ requested ) , 'defaultRelations' ) ; return array_merge ( $ relations , $ nestedRelations ) ; }

Get a list of default relations including nested relations.

@param  array $requested
@return array

Get a list of default relations including nested relations .


protected function extractRelations(array $relations): array
    {
        $available = $this->availableRelations();

        return array_filter($this->mapRelations($relations, function ($relation, $constraint) {
            $identifier = explode('.', $relation)[0];
            $constraint = $identifier === $relation ? $constraint : null;

            return [$identifier => $constraint ?: $this->resolveQueryConstraint($identifier)];
        }), function ($relation) use ($available) {
            return array_has($available, explode(':', $relation)[0]);
        }, ARRAY_FILTER_USE_KEY);
    }

protected function extractRelations ( array $ relations ) : array { $ available = $ this -> availableRelations ( ) ; return array_filter ( $ this -> mapRelations ( $ relations , function ( $ relation , $ constraint ) { $ identifier = explode ( '.' , $ relation ) [ 0 ] ; $ constraint = $ identifier === $ relation ? $ constraint : null ; return [ $ identifier => $ constraint ? : $ this -> resolveQueryConstraint ( $ identifier ) ] ; } ) , function ( $ relation ) use ( $ available ) { return array_has ( $ available , explode ( ':' , $ relation ) [ 0 ] ) ; } , ARRAY_FILTER_USE_KEY ) ; }

Extract available root relations from the given list of relations.

@param  array $relations
@return array

Extract available root relations from the given list of relations .


protected function extractChildRelations(array $relations, string $identifier): array
    {
        return array_reduce(array_keys($relations), function ($nested, $relation) use ($relations, $identifier) {
            if (! starts_with($relation, "$identifier.")) {
                return $nested;
            }

            $nestedIdentifier = explode('.', $relation);
            array_shift($nestedIdentifier);

            return array_merge($nested, [implode('.', $nestedIdentifier) => $relations[$relation]]);
        }, []);
    }

protected function extractChildRelations ( array $ relations , string $ identifier ) : array { return array_reduce ( array_keys ( $ relations ) , function ( $ nested , $ relation ) use ( $ relations , $ identifier ) { if ( ! starts_with ( $ relation , "$identifier." ) ) { return $ nested ; } $ nestedIdentifier = explode ( '.' , $ relation ) ; array_shift ( $ nestedIdentifier ) ; return array_merge ( $ nested , [ implode ( '.' , $ nestedIdentifier ) => $ relations [ $ relation ] ] ) ; } , [ ] ) ; }

Extract all nested relations under a given identifier.

@param  array  $relations
@param  string $identifier
@return array

Extract all nested relations under a given identifier .


protected function wrapChildRelations(array $nestedRelations, string $relation): array
    {
        return $this->mapRelations($nestedRelations, function ($nestedRelation, $constraint) use ($relation) {
            return ["$relation.$nestedRelation" => $constraint];
        });
    }

protected function wrapChildRelations ( array $ nestedRelations , string $ relation ) : array { return $ this -> mapRelations ( $ nestedRelations , function ( $ nestedRelation , $ constraint ) use ( $ relation ) { return [ "$relation.$nestedRelation" => $ constraint ] ; } ) ; }

Wrap the identifier of each relation of the given list of nested relations with
the parent relation identifier using dot notation.

@param  array  $nestedRelations
@param  string $relation
@return array

Wrap the identifier of each relation of the given list of nested relations with the parent relation identifier using dot notation .


protected function applyQueryConstraints(array $relations): array
    {
        return $this->mapRelations($relations, function ($relation, $constraint) {
            return [$relation => is_callable($constraint) ? $constraint : $this->resolveQueryConstraint($relation)];
        });
    }

protected function applyQueryConstraints ( array $ relations ) : array { return $ this -> mapRelations ( $ relations , function ( $ relation , $ constraint ) { return [ $ relation => is_callable ( $ constraint ) ? $ constraint : $ this -> resolveQueryConstraint ( $ relation ) ] ; } ) ; }

Applies any query constraints defined in the transformer to the list of relaations.

@param  array $relations
@return array

Applies any query constraints defined in the transformer to the list of relaations .


protected function resolveQueryConstraint(string $identifier)
    {
        if (! method_exists($this, $method = 'load' . ucfirst(camel_case($identifier)))) {
            return null;
        }

        return function ($query) use ($method) {
            return $this->$method($query);
        };
    }

protected function resolveQueryConstraint ( string $ identifier ) { if ( ! method_exists ( $ this , $ method = 'load' . ucfirst ( camel_case ( $ identifier ) ) ) ) { return null ; } return function ( $ query ) use ( $ method ) { return $ this -> $ method ( $ query ) ; } ; }

Resolve a query constraint for a given relation identifier.

@param  string $identifier
@return \Closure|null

Resolve a query constraint for a given relation identifier .


protected function resolveRelation(Model $model, string $identifier)
    {
        $identifier = camel_case($identifier);
        $relation = $model->$identifier;

        if (method_exists($this, $method = 'filter' . ucfirst($identifier))) {
            return $this->$method($relation);
        }

        return $relation;
    }

protected function resolveRelation ( Model $ model , string $ identifier ) { $ identifier = camel_case ( $ identifier ) ; $ relation = $ model -> $ identifier ; if ( method_exists ( $ this , $ method = 'filter' . ucfirst ( $ identifier ) ) ) { return $ this -> $ method ( $ relation ) ; } return $ relation ; }

Resolve a relation from a model instance and an identifier.

@param  \Illuminate\Database\Eloquent\Model $model
@param  string                              $identifier
@return mixed

Resolve a relation from a model instance and an identifier .


protected function mappedTransformers(array $relations): array
    {
        $transformers = collect($this->availableRelations())->filter(function ($transformer) {
            return ! is_null($transformer);
        })->map(function ($transformer) {
            return $this->resolveTransformer($transformer);
        })->all();

        return array_intersect_key($transformers, $relations);
    }

protected function mappedTransformers ( array $ relations ) : array { $ transformers = collect ( $ this -> availableRelations ( ) ) -> filter ( function ( $ transformer ) { return ! is_null ( $ transformer ) ; } ) -> map ( function ( $ transformer ) { return $ this -> resolveTransformer ( $ transformer ) ; } ) -> all ( ) ; return array_intersect_key ( $ transformers , $ relations ) ; }

Resolve a list of transformers from a list of relations mapped to transformers.

@param  array $relations
@return array

Resolve a list of transformers from a list of relations mapped to transformers .


protected function resource($data = null, $transformer = null, string $resourceKey = null): ResourceInterface
    {
        if ($data instanceof ResourceInterface) {
            return $data;
        }

        $resourceFactory = $this->resolveContainer()->make(ResourceFactory::class);

        return $resourceFactory->make($data, $transformer, $resourceKey);
    }

protected function resource ( $ data = null , $ transformer = null , string $ resourceKey = null ) : ResourceInterface { if ( $ data instanceof ResourceInterface ) { return $ data ; } $ resourceFactory = $ this -> resolveContainer ( ) -> make ( ResourceFactory :: class ) ; return $ resourceFactory -> make ( $ data , $ transformer , $ resourceKey ) ; }

Make a resource.

@param  mixed                                                          $data
@param  \Flugg\Responder\Transformers\Transformer|string|callable|null $transformer
@param  string|null                                                    $resourceKey
@return \League\Fractal\Resource\ResourceInterface


protected function includeResource(string $identifier, $data, array $parameters): ResourceInterface
    {
        $transformer = $this->mappedTransformerClass($identifier);

        if (method_exists($this, $method = 'include' . ucfirst(camel_case($identifier)))) {
            $resource = $this->resource($this->$method($data, collect($parameters)), $transformer, $identifier);
        } elseif ($data instanceof Model) {
            $resource = $this->includeResourceFromModel($data, $identifier, $transformer);
        } else {
            throw new LogicException('Relation [' . $identifier . '] not found in [' . get_class($this) . '].');
        }

        return $resource;
    }

protected
function
includeResource
(
string
$
identifier
,
$
data
,
array
$
parameters
)
:
ResourceInterface
{
$
transformer
=
$
this
->
mappedTransformerClass
(
$
identifier
)
;
if
(
method_exists
(
$
this
,
$
method
=
'include'
.
ucfirst
(
camel_case
(
$
identifier
)
)
)
)
{
$
resource
=
$
this
->
resource
(
$
this
->
$
method
(
$
data
,
collect
(
$
parameters
)
)
,
$
transformer
,
$
identifier
)
;
}
elseif
(
$
data
instanceof
Model
)
{
$
resource
=
$
this
->
includeResourceFromModel
(
$
data
,
$
identifier
,
$
transformer
)
;
}
else
{
throw
new
LogicException
(
'Relation ['
.
$
identifier
.
'] not found in ['
.
get_class
(
$
this
)
.
'].'
)
;
}
return
$
resource
;
}

Include a related resource.

@param  string $identifier
@param  mixed  $data
@param  array  $parameters
@return \League\Fractal\Resource\ResourceInterface
@throws \LogicException


protected function includeResourceFromModel(Model $model, string $identifier, $transformer = null): ResourceInterface
    {
        $data = $this->resolveRelation($model, $identifier);

        if (! $this->shouldCacheResource($data)) {
            return $this->resource($data, $transformer, $identifier);
        } elseif (key_exists($identifier, $this->resources)) {
            return $this->resources[$identifier]->setData($data);
        }

        return $this->resources[$identifier] = $this->resource($data, $transformer, $identifier);
    }

protected function includeResourceFromModel ( Model $ model , string $ identifier , $ transformer = null ) : ResourceInterface { $ data = $ this -> resolveRelation ( $ model , $ identifier ) ; if ( ! $ this -> shouldCacheResource ( $ data ) ) { return $ this -> resource ( $ data , $ transformer , $ identifier ) ; } elseif ( key_exists ( $ identifier , $ this -> resources ) ) { return $ this -> resources [ $ identifier ] -> setData ( $ data ) ; } return $ this -> resources [ $ identifier ] = $ this -> resource ( $ data , $ transformer , $ identifier ) ; }

Include a related resource from a model and cache the resource type for following calls.

@param  \Illuminate\Database\Eloquent\Model                            $model
@param  string                                                         $identifier
@param  \Flugg\Responder\Transformers\Transformer|string|callable|null $transformer
@return \League\Fractal\Resource\ResourceInterface

Include a related resource from a model and cache the resource type for following calls .


protected function shouldCacheResource($data): bool
    {
        return is_array($data) || $data instanceof Countable ? count($data) > 0 : is_null($data);
    }

protected function shouldCacheResource ( $ data ) : bool { return is_array ( $ data ) || $ data instanceof Countable ? count ( $ data ) > 0 : is_null ( $ data ) ; }

Indicates if the resource should be cached.

@param  mixed $data
@return bool

Indicates if the resource should be cached .


public function make($data = null, $transformer = null, string $resourceKey = null): ResourceInterface
    {
        if ($data instanceof ResourceInterface) {
            return $this->makeFromResource($data, $transformer, $resourceKey);
        } elseif (is_null($data = $this->normalizer->normalize($data))) {
            return $this->instatiateResource($data, null, $resourceKey);
        }

        $transformer = $this->resolveTransformer($data, $transformer);
        $resourceKey = $this->resolveResourceKey($data, $resourceKey);

        return $this->instatiateResource($data, $transformer, $resourceKey);
    }

public function make ( $ data = null , $ transformer = null , string $ resourceKey = null ) : ResourceInterface { if ( $ data instanceof ResourceInterface ) { return $ this -> makeFromResource ( $ data , $ transformer , $ resourceKey ) ; } elseif ( is_null ( $ data = $ this -> normalizer -> normalize ( $ data ) ) ) { return $ this -> instatiateResource ( $ data , null , $ resourceKey ) ; } $ transformer = $ this -> resolveTransformer ( $ data , $ transformer ) ; $ resourceKey = $ this -> resolveResourceKey ( $ data , $ resourceKey ) ; return $ this -> instatiateResource ( $ data , $ transformer , $ resourceKey ) ; }

Make resource from the given data.

@param  mixed                                                          $data
@param  \Flugg\Responder\Transformers\Transformer|string|callable|null $transformer
@param  string|null                                                    $resourceKey
@return \League\Fractal\Resource\ResourceInterface


public function makeFromResource(ResourceInterface $resource, $transformer = null, string $resourceKey = null): ResourceInterface
    {
        $transformer = $this->resolveTransformer($resource->getData(), $transformer ?: $resource->getTransformer());
        $resourceKey = $this->resolveResourceKey($resource->getData(), $resourceKey ?: $resource->getResourceKey());

        return $resource->setTransformer($transformer)->setResourceKey($resourceKey);
    }

public function makeFromResource ( ResourceInterface $ resource , $ transformer = null , string $ resourceKey = null ) : ResourceInterface { $ transformer = $ this -> resolveTransformer ( $ resource -> getData ( ) , $ transformer ? : $ resource -> getTransformer ( ) ) ; $ resourceKey = $ this -> resolveResourceKey ( $ resource -> getData ( ) , $ resourceKey ? : $ resource -> getResourceKey ( ) ) ; return $ resource -> setTransformer ( $ transformer ) -> setResourceKey ( $ resourceKey ) ; }

Make resource from the given resource.

@param  \League\Fractal\Resource\ResourceInterface                     $resource
@param  \Flugg\Responder\Transformers\Transformer|string|callable|null $transformer
@param  string|null                                                    $resourceKey
@return \League\Fractal\Resource\ResourceInterface


protected function instatiateResource($data, $transformer = null, string $resourceKey = null): ResourceInterface
    {
        if (is_null($data)) {
            return new NullResource(null, null, $resourceKey);
        } elseif ($this->shouldCreateCollection($data)) {
            return new CollectionResource($data, $transformer, $resourceKey);
        } elseif (is_scalar($data)) {
            return new Primitive($data, $transformer, $resourceKey);
        }

        return new ItemResource($data, $transformer, $resourceKey);
    }

protected function instatiateResource ( $ data , $ transformer = null , string $ resourceKey = null ) : ResourceInterface { if ( is_null ( $ data ) ) { return new NullResource ( null , null , $ resourceKey ) ; } elseif ( $ this -> shouldCreateCollection ( $ data ) ) { return new CollectionResource ( $ data , $ transformer , $ resourceKey ) ; } elseif ( is_scalar ( $ data ) ) { return new Primitive ( $ data , $ transformer , $ resourceKey ) ; } return new ItemResource ( $ data , $ transformer , $ resourceKey ) ; }

Instatiate a new resource instance.

@param  mixed                                                   $data
@param  \Flugg\Responder\Transformers\Transformer|callable|null $transformer
@param  string|null                                             $resourceKey
@return \League\Fractal\Resource\ResourceInterface


protected function shouldCreateCollection($data): bool
    {
        if (is_array($data)) {
            return ! Arr::isAssoc($data) && ! is_scalar(Arr::first($data));
        }

        return $data instanceof Traversable;
    }

protected function shouldCreateCollection ( $ data ) : bool { if ( is_array ( $ data ) ) { return ! Arr :: isAssoc ( $ data ) && ! is_scalar ( Arr :: first ( $ data ) ) ; } return $ data instanceof Traversable ; }

Indicates if the data belongs to a collection resource.

@param  mixed $data
@return bool

Indicates if the data belongs to a collection resource .


protected function resolveResourceKey($data, string $resourceKey = null)
    {
        return isset($resourceKey) ? $resourceKey : $this->resourceKeyResolver->resolve($data);
    }

protected function resolveResourceKey ( $ data , string $ resourceKey = null ) { return isset ( $ resourceKey ) ? $ resourceKey : $ this -> resourceKeyResolver -> resolve ( $ data ) ; }

Resolve a resource key.

@param  mixed       $data
@param  string|null $resourceKey
@return null|string


public function decorator($decorator)
    {
        $decorators = is_array($decorator) ? $decorator : func_get_args();

        foreach ($decorators as $decorator) {
            $this->responseFactory = new $decorator($this->responseFactory);
        };

        return $this;
    }

public function decorator ( $ decorator ) { $ decorators = is_array ( $ decorator ) ? $ decorator : func_get_args ( ) ; foreach ( $ decorators as $ decorator ) { $ this -> responseFactory = new $ decorator ( $ this -> responseFactory ) ; } ; return $ this ; }

Decorate the response with the given decorator.

@param  string[]|string $decorator
@return $this

Decorate the response with the given decorator .


public function respond(int $status = null, array $headers = []): JsonResponse
    {
        if (! is_null($status)) {
            $this->setStatusCode($status);
        }

        return $this->responseFactory->make($this->getOutput(), $this->status, $headers);
    }

public function respond ( int $ status = null , array $ headers = [ ] ) : JsonResponse { if ( ! is_null ( $ status ) ) { $ this -> setStatusCode ( $ status ) ; } return $ this -> responseFactory -> make ( $ this -> getOutput ( ) , $ this -> status , $ headers ) ; }

Respond with a successful response.

@param  int|null $status
@param  array    $headers
@return \Illuminate\Http\JsonResponse


public function normalize($data = null)
    {
        if ($this->isInstanceOf($data, [Builder::class, EloquentBuilder::class, CursorPaginator::class])) {
            return $data->get();
        } elseif ($data instanceof Paginator) {
            return $data->getCollection();
        } elseif ($data instanceof Relation) {
            return $this->normalizeRelation($data);
        }

        return $data;
    }

public function normalize ( $ data = null ) { if ( $ this -> isInstanceOf ( $ data , [ Builder :: class , EloquentBuilder :: class , CursorPaginator :: class ] ) ) { return $ data -> get ( ) ; } elseif ( $ data instanceof Paginator ) { return $ data -> getCollection ( ) ; } elseif ( $ data instanceof Relation ) { return $ this -> normalizeRelation ( $ data ) ; } return $ data ; }

Normalize the data for a resource.

@param  mixed $data
@return mixed


protected function normalizeRelation(Relation $relation)
    {
        if ($this->isInstanceOf($relation, [BelongsTo::class, HasOne::class, MorphOne::class, MorphTo::class])) {
            return $relation->first();
        }

        return $relation->get();
    }

protected function normalizeRelation ( Relation $ relation ) { if ( $ this -> isInstanceOf ( $ relation , [ BelongsTo :: class , HasOne :: class , MorphOne :: class , MorphTo :: class ] ) ) { return $ relation -> first ( ) ; } return $ relation -> get ( ) ; }

Normalize a relationship.

@param  \Illuminate\Database\Eloquent\Relations\Relation $relation
@return \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|null


public function transform($data = null, $transformer = null, string $resourceKey = null): SuccessResponseBuilder
    {
        $this->transformBuilder->resource($data, $transformer, $resourceKey);

        return $this;
    }

public function transform ( $ data = null , $ transformer = null , string $ resourceKey = null ) : SuccessResponseBuilder { $ this -> transformBuilder -> resource ( $ data , $ transformer , $ resourceKey ) ; return $ this ; }

Set resource data for the transformation.

@param  mixed                                                          $data
@param  \Flugg\Responder\Transformers\Transformer|callable|string|null $transformer
@param  string|null                                                    $resourceKey
@return self

Set resource data for the transformation .


protected function convert(Exception $exception, array $convert)
    {
        foreach ($convert as $source => $target) {
            if ($exception instanceof $source) {
                if (is_callable($target)) {
                    $target($exception);
                }

                throw new $target;
            }
        }
    }

protected function convert ( Exception $ exception , array $ convert ) { foreach ( $ convert as $ source => $ target ) { if ( $ exception instanceof $ source ) { if ( is_callable ( $ target ) ) { $ target ( $ exception ) ; } throw new $ target ; } } }

Convert an exception to another exception

@param  \Exception $exception
@param  array      $convert
@return void


protected function convertDefaultException(Exception $exception)
    {
        $this->convert($exception, array_diff_key([
            AuthenticationException::class => UnauthenticatedException::class,
            AuthorizationException::class => UnauthorizedException::class,
            NotFoundHttpException::class => PageNotFoundException::class,
            ModelNotFoundException::class => PageNotFoundException::class,
            BaseRelationNotFoundException::class => RelationNotFoundException::class,
            ValidationException::class => function ($exception) {
                throw new ValidationFailedException($exception->validator);
            },
        ], array_flip($this->dontConvert)));
    }

protected function convertDefaultException ( Exception $ exception ) { $ this -> convert ( $ exception , array_diff_key ( [ AuthenticationException :: class => UnauthenticatedException :: class , AuthorizationException :: class => UnauthorizedException :: class , NotFoundHttpException :: class => PageNotFoundException :: class , ModelNotFoundException :: class => PageNotFoundException :: class , BaseRelationNotFoundException :: class => RelationNotFoundException :: class , ValidationException :: class => function ( $ exception ) { throw new ValidationFailedException ( $ exception -> validator ) ; } , ] , array_flip ( $ this -> dontConvert ) ) ) ; }

Convert a default exception to an API exception.

@param  \Exception $exception
@return void

Convert a default exception to an API exception .


protected function renderResponse(HttpException $exception): JsonResponse
    {
        return app(Responder::class)
            ->error($exception->errorCode(), $exception->message())
            ->data($exception->data())
            ->respond($exception->statusCode(), $exception->getHeaders());
    }

protected function renderResponse ( HttpException $ exception ) : JsonResponse { return app ( Responder :: class ) -> error ( $ exception -> errorCode ( ) , $ exception -> message ( ) ) -> data ( $ exception -> data ( ) ) -> respond ( $ exception -> statusCode ( ) , $ exception -> getHeaders ( ) ) ; }

Render an error response from an API exception.

@param  \Flugg\Responder\Exceptions\Http\HttpException $exception
@return \Illuminate\Http\JsonResponse

Render an error response from an API exception .


public function make($data = null, $transformer = null, string $resourceKey = null): TransformBuilder
    {
        return $this->transformBuilder->resource($data, $transformer, $resourceKey)->serializer(new NoopSerializer);
    }

public function make ( $ data = null , $ transformer = null , string $ resourceKey = null ) : TransformBuilder { return $ this -> transformBuilder -> resource ( $ data , $ transformer , $ resourceKey ) -> serializer ( new NoopSerializer ) ; }

Make a new transformation to transform data without serializing.

@param  mixed                                                          $data
@param  \Flugg\Responder\Transformers\Transformer|callable|string|null $transformer
@param  string|null                                                    $resourceKey
@return \Flugg\Responder\TransformBuilder

Make a new transformation to transform data without serializing .


protected function configureTerminal() : void
    {
        $this->assertTerminalIsValidTTY();

        $this->terminal->disableCanonicalMode();
        $this->terminal->disableEchoBack();
        $this->terminal->disableCursor();
        $this->terminal->clear();
    }

protected function configureTerminal ( ) : void { $ this -> assertTerminalIsValidTTY ( ) ; $ this -> terminal -> disableCanonicalMode ( ) ; $ this -> terminal -> disableEchoBack ( ) ; $ this -> terminal -> disableCursor ( ) ; $ this -> terminal -> clear ( ) ; }

Configure the terminal to work with CliMenu


public function addItems(array $items) : void
    {
        foreach ($items as $item) {
            $this->items[] = $item;
        }

        $this->selectFirstItem();
    }

public function addItems ( array $ items ) : void { foreach ( $ items as $ item ) { $ this -> items [ ] = $ item ; } $ this -> selectFirstItem ( ) ; }


public function setItems(array $items) : void
    {
        $this->selectedItem = null;
        $this->items = $items;

        $this->selectFirstItem();
    }

public function setItems ( array $ items ) : void { $ this -> selectedItem = null ; $ this -> items = $ items ; $ this -> selectFirstItem ( ) ; }


private function selectFirstItem() : void
    {
        if (null === $this->selectedItem) {
            foreach ($this->items as $key => $item) {
                if ($item->canSelect()) {
                    $this->selectedItem = $key;
                    break;
                }
            }
        }
    }

private function selectFirstItem ( ) : void { if ( null === $ this -> selectedItem ) { foreach ( $ this -> items as $ key => $ item ) { if ( $ item -> canSelect ( ) ) { $ this -> selectedItem = $ key ; break ; } } } }

Set the selected pointer to the first selectable item


public function addCustomControlMapping(string $input, callable $callable) : void
    {
        if (isset($this->defaultControlMappings[$input]) || isset($this->customControlMappings[$input])) {
            throw new \InvalidArgumentException('Cannot rebind this input');
        }

        $this->customControlMappings[$input] = $callable;
    }

public
function
addCustomControlMapping
(
string
$
input
,
callable
$
callable
)
:
void
{
if
(
isset
(
$
this
->
defaultControlMappings
[
$
input
]
)
||
isset
(
$
this
->
customControlMappings
[
$
input
]
)
)
{
throw
new
\
InvalidArgumentException
(
'Cannot rebind this input'
)
;
}
$
this
->
customControlMappings
[
$
input
]
=
$
callable
;
}


public function removeCustomControlMapping(string $input) : void
    {
        if (!isset($this->customControlMappings[$input])) {
            throw new \InvalidArgumentException('This input is not registered');
        }

        unset($this->customControlMappings[$input]);
    }

public
function
removeCustomControlMapping
(
string
$
input
)
:
void
{
if
(
!
isset
(
$
this
->
customControlMappings
[
$
input
]
)
)
{
throw
new
\
InvalidArgumentException
(
'This input is not registered'
)
;
}
unset
(
$
this
->
customControlMappings
[
$
input
]
)
;
}


private function display() : void
    {
        $this->draw();

        $reader = new NonCanonicalReader($this->terminal);
        $reader->addControlMappings($this->defaultControlMappings);

        while ($this->isOpen()) {
            $char = $reader->readCharacter();
            if (!$char->isHandledControl()) {
                $rawChar = $char->get();
                if (isset($this->customControlMappings[$rawChar])) {
                    $this->customControlMappings[$rawChar]($this);
                }
                continue;
            }

            switch ($char->getControl()) {
                case InputCharacter::UP:
                case InputCharacter::DOWN:
                    $this->moveSelectionVertically($char->getControl());
                    $this->draw();
                    break;
                case InputCharacter::LEFT:
                case InputCharacter::RIGHT:
                    $this->moveSelectionHorizontally($char->getControl());
                    $this->draw();
                    break;
                case InputCharacter::ENTER:
                    $this->executeCurrentItem();
                    break;
            }
        }
    }

private function display ( ) : void { $ this -> draw ( ) ; $ reader = new NonCanonicalReader ( $ this -> terminal ) ; $ reader -> addControlMappings ( $ this -> defaultControlMappings ) ; while ( $ this -> isOpen ( ) ) { $ char = $ reader -> readCharacter ( ) ; if ( ! $ char -> isHandledControl ( ) ) { $ rawChar = $ char -> get ( ) ; if ( isset ( $ this -> customControlMappings [ $ rawChar ] ) ) { $ this -> customControlMappings [ $ rawChar ] ( $ this ) ; } continue ; } switch ( $ char -> getControl ( ) ) { case InputCharacter :: UP : case InputCharacter :: DOWN : $ this -> moveSelectionVertically ( $ char -> getControl ( ) ) ; $ this -> draw ( ) ; break ; case InputCharacter :: LEFT : case InputCharacter :: RIGHT : $ this -> moveSelectionHorizontally ( $ char -> getControl ( ) ) ; $ this -> draw ( ) ; break ; case InputCharacter :: ENTER : $ this -> executeCurrentItem ( ) ; break ; } } }


public function getSelectedItem() : MenuItemInterface
    {
        if (null === $this->selectedItem) {
            throw new \RuntimeException('No selected item');
        }

        $item = $this->items[$this->selectedItem];
        return $item instanceof SplitItem
            ? $item->getSelectedItem()
            : $item;
    }

public
function
getSelectedItem
(
)
:
MenuItemInterface
{
if
(
===
$
this
->
selectedItem
)
{
throw
new
\
RuntimeException
(
'No selected item'
)
;
}
$
item
=
$
this
->
items
[
$
this
->
selectedItem
]
;
return
$
item
instanceof
SplitItem
$
item
->
getSelectedItem
(
)
:
$
item
;
}

Retrieve the item the user actually selected


protected function executeCurrentItem() : void
    {
        $item = $this->getSelectedItem();

        if ($item->canSelect()) {
            $callable = $item->getSelectAction();
            if ($callable) {
                $callable($this);
            }
        }
    }

protected function executeCurrentItem ( ) : void { $ item = $ this -> getSelectedItem ( ) ; if ( $ item -> canSelect ( ) ) { $ callable = $ item -> getSelectAction ( ) ; if ( $ callable ) { $ callable ( $ this ) ; } } }


public function redraw(bool $clear = false) : void
    {
        if ($clear) {
            $this->terminal->clear();
        }

        $this->assertOpen();
        $this->draw();
    }

public function redraw ( bool $ clear = false ) : void { if ( $ clear ) { $ this -> terminal -> clear ( ) ; } $ this -> assertOpen ( ) ; $ this -> draw ( ) ; }

If true we clear the whole terminal screen, useful
for example when reducing the width of the menu, to not
leave leftovers of the previous wider menu.

Redraw the menu

If true we clear the whole terminal screen useful for example when reducing the width of the menu to not leave leftovers of the previous wider menu .


protected function draw() : void
    {
        $frame = new Frame;

        $frame->newLine(2);

        if ($this->style->getBorderTopWidth() > 0) {
            $frame->addRows($this->style->getBorderTopRows());
        }

        if ($this->style->getPaddingTopBottom() > 0) {
            $frame->addRows($this->style->getPaddingTopBottomRows());
        }

        if ($this->title) {
            $frame->addRows($this->drawMenuItem(new StaticItem($this->title)));
            $frame->addRows($this->drawMenuItem(new LineBreakItem($this->style->getTitleSeparator())));
        }

        array_map(function ($item, $index) use ($frame) {
            $frame->addRows($this->drawMenuItem($item, $index === $this->selectedItem));
        }, $this->items, array_keys($this->items));

        if ($this->style->getPaddingTopBottom() > 0) {
            $frame->addRows($this->style->getPaddingTopBottomRows());
        }

        if ($this->style->getBorderBottomWidth() > 0) {
            $frame->addRows($this->style->getBorderBottomRows());
        }

        $frame->newLine(2);

        $this->terminal->moveCursorToTop();
        foreach ($frame->getRows() as $row) {
            if ($row == "\n") {
                $this->terminal->clearLine();
            }
            $this->terminal->write($row);
        }
        $this->terminal->clearDown();

        $this->currentFrame = $frame;
    }

protected function draw ( ) : void { $ frame = new Frame ; $ frame -> newLine ( 2 ) ; if ( $ this -> style -> getBorderTopWidth ( ) > 0 ) { $ frame -> addRows ( $ this -> style -> getBorderTopRows ( ) ) ; } if ( $ this -> style -> getPaddingTopBottom ( ) > 0 ) { $ frame -> addRows ( $ this -> style -> getPaddingTopBottomRows ( ) ) ; } if ( $ this -> title ) { $ frame -> addRows ( $ this -> drawMenuItem ( new StaticItem ( $ this -> title ) ) ) ; $ frame -> addRows ( $ this -> drawMenuItem ( new LineBreakItem ( $ this -> style -> getTitleSeparator ( ) ) ) ) ; } array_map ( function ( $ item , $ index ) use ( $ frame ) { $ frame -> addRows ( $ this -> drawMenuItem ( $ item , $ index === $ this -> selectedItem ) ) ; } , $ this -> items , array_keys ( $ this -> items ) ) ; if ( $ this -> style -> getPaddingTopBottom ( ) > 0 ) { $ frame -> addRows ( $ this -> style -> getPaddingTopBottomRows ( ) ) ; } if ( $ this -> style -> getBorderBottomWidth ( ) > 0 ) { $ frame -> addRows ( $ this -> style -> getBorderBottomRows ( ) ) ; } $ frame -> newLine ( 2 ) ; $ this -> terminal -> moveCursorToTop ( ) ; foreach ( $ frame -> getRows ( ) as $ row ) { if ( $ row == "\n" ) { $ this -> terminal -> clearLine ( ) ; } $ this -> terminal -> write ( $ row ) ; } $ this -> terminal -> clearDown ( ) ; $ this -> currentFrame = $ frame ; }


protected function drawMenuItem(MenuItemInterface $item, bool $selected = false) : array
    {
        $rows = $item->getRows($this->style, $selected);

        if ($item instanceof SplitItem) {
            $selected = false;
        }

        $invertedColoursSetCode = $selected
            ? $this->style->getInvertedColoursSetCode()
            : '';
        $invertedColoursUnsetCode = $selected
            ? $this->style->getInvertedColoursUnsetCode()
            : '';

        if ($this->style->getBorderLeftWidth() || $this->style->getBorderRightWidth()) {
            $borderColour = $this->style->getBorderColourCode();
        } else {
            $borderColour = '';
        }

        return array_map(function ($row) use ($invertedColoursSetCode, $invertedColoursUnsetCode, $borderColour) {
            return sprintf(
                "%s%s%s%s%s%s%s%s%s%s%s%s\n",
                str_repeat(' ', $this->style->getMargin()),
                $borderColour,
                str_repeat(' ', $this->style->getBorderLeftWidth()),
                $this->style->getColoursSetCode(),
                $invertedColoursSetCode,
                str_repeat(' ', $this->style->getPaddingLeftRight()),
                $row,
                str_repeat(' ', $this->style->getRightHandPadding(mb_strlen(s::stripAnsiEscapeSequence($row)))),
                $invertedColoursUnsetCode,
                $borderColour,
                str_repeat(' ', $this->style->getBorderRightWidth()),
                $this->style->getColoursResetCode()
            );
        }, $rows);
    }

protected
function
drawMenuItem
(
MenuItemInterface
$
item
,
bool
$
selected
=
false
)
:
array
{
$
rows
=
$
item
->
getRows
(
$
this
->
style
,
$
selected
)
;
if
(
$
item
instanceof
SplitItem
)
{
$
selected
=
false
;
}
$
invertedColoursSetCode
=
$
selected
$
this
->
style
->
getInvertedColoursSetCode
(
)
:
''
;
$
invertedColoursUnsetCode
=
$
selected
$
this
->
style
->
getInvertedColoursUnsetCode
(
)
:
''
;
if
(
$
this
->
style
->
getBorderLeftWidth
(
)
||
$
this
->
style
->
getBorderRightWidth
(
)
)
{
$
borderColour
=
$
this
->
style
->
getBorderColourCode
(
)
;
}
else
{
$
borderColour
=
''
;
}
return
array_map
(
function
(
$
row
)
use
(
$
invertedColoursSetCode
,
$
invertedColoursUnsetCode
,
$
borderColour
)
{
return
sprintf
(
"%s%s%s%s%s%s%s%s%s%s%s%s\n"
,
str_repeat
(
' '
,
$
this
->
style
->
getMargin
(
)
)
,
$
borderColour
,
str_repeat
(
' '
,
$
this
->
style
->
getBorderLeftWidth
(
)
)
,
$
this
->
style
->
getColoursSetCode
(
)
,
$
invertedColoursSetCode
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
$
row
,
str_repeat
(
' '
,
$
this
->
style
->
getRightHandPadding
(
mb_strlen
(
s
::
stripAnsiEscapeSequence
(
$
row
)
)
)
)
,
$
invertedColoursUnsetCode
,
$
borderColour
,
str_repeat
(
' '
,
$
this
->
style
->
getBorderRightWidth
(
)
)
,
$
this
->
style
->
getColoursResetCode
(
)
)
;
}
,
$
rows
)
;
}


public function close() : void
    {
        $menu = $this;

        do {
            $menu->closeThis();
            $menu = $menu->getParent();
        } while (null !== $menu);

        $this->tearDownTerminal();
    }

public function close ( ) : void { $ menu = $ this ; do { $ menu -> closeThis ( ) ; $ menu = $ menu -> getParent ( ) ; } while ( null !== $ menu ) ; $ this -> tearDownTerminal ( ) ; }

Close the menu

@throws InvalidTerminalException


private function setDefaultSelectedItem() : void
    {
        foreach ($this->items as $index => $item) {
            if ($item->canSelect()) {
                $this->canBeSelected = true;
                $this->selectedItemIndex = $index;
                return;
            }
        }

        $this->canBeSelected = false;
        $this->selectedItemIndex = null;
    }

private function setDefaultSelectedItem ( ) : void { foreach ( $ this -> items as $ index => $ item ) { if ( $ item -> canSelect ( ) ) { $ this -> canBeSelected = true ; $ this -> selectedItemIndex = $ index ; return ; } } $ this -> canBeSelected = false ; $ this -> selectedItemIndex = null ; }


public function canSelectIndex(int $index) : bool
    {
        return isset($this->items[$index]) && $this->items[$index]->canSelect();
    }

public function canSelectIndex ( int $ index ) : bool { return isset ( $ this -> items [ $ index ] ) && $ this -> items [ $ index ] -> canSelect ( ) ; }

Is there an item with this index and can it be
selected?


public function setSelectedItemIndex(int $index) : void
    {
        if (!isset($this->items[$index])) {
            throw new \InvalidArgumentException(sprintf('Index: "%s" does not exist', $index));
        }

        $this->selectedItemIndex = $index;
    }

public
function
setSelectedItemIndex
(
int
$
index
)
:
void
{
if
(
!
isset
(
$
this
->
items
[
$
index
]
)
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
'Index: "%s" does not exist'
,
$
index
)
)
;
}
$
this
->
selectedItemIndex
=
$
index
;
}

Set the item index which should be selected. If the item does
not exist then throw an exception.

Set the item index which should be selected . If the item does not exist then throw an exception .


public function getSelectedItem() : MenuItemInterface
    {
        if (null === $this->selectedItemIndex) {
            throw new \RuntimeException('No item is selected');
        }

        return $this->items[$this->selectedItemIndex];
    }

public
function
getSelectedItem
(
)
:
MenuItemInterface
{
if
(
===
$
this
->
selectedItemIndex
)
{
throw
new
\
RuntimeException
(
'No item is selected'
)
;
}
return
$
this
->
items
[
$
this
->
selectedItemIndex
]
;
}

Get the currently selected item - if no items are selectable
then throw an exception.

Get the currently selected item - if no items are selectable then throw an exception .


public static function wordwrap(string $string, int $width, string $break = "\n") : string
    {
        return implode(
            $break,
            array_map(function (string $line) use ($width, $break) {
                $line = rtrim($line);
                if (mb_strlen($line) <= $width) {
                    return $line;
                }

                $words  = explode(' ', $line);
                $line   = '';
                $actual = '';
                foreach ($words as $word) {
                    if (mb_strlen($actual . $word) <= $width) {
                        $actual .= $word . ' ';
                    } else {
                        if ($actual !== '') {
                            $line .= rtrim($actual) . $break;
                        }
                        $actual = $word . ' ';
                    }
                }
                return $line . trim($actual);
            }, explode("\n", $string))
        );
    }

public
static
function
wordwrap
(
string
$
string
,
int
$
width
,
string
$
break
=
"\n"
)
:
string
{
return
implode
(
$
break
,
array_map
(
function
(
string
$
line
)
use
(
$
width
,
$
break
)
{
$
line
=
rtrim
(
$
line
)
;
if
(
mb_strlen
(
$
line
)
<=
$
width
)
{
return
$
line
;
}
$
words
=
explode
(
' '
,
$
line
)
;
$
line
=
''
;
$
actual
=
''
;
foreach
(
$
words
as
$
word
)
{
if
(
mb_strlen
(
$
actual
.
$
word
)
<=
$
width
)
{
$
actual
.=
$
word
.
' '
;
}
else
{
if
(
$
actual
!==
''
)
{
$
line
.=
rtrim
(
$
actual
)
.
$
break
;
}
$
actual
=
$
word
.
' '
;
}
}
return
$
line
.
trim
(
$
actual
)
;
}
,
explode
(
"\n"
,
$
string
)
)
)
;
}

Minimal multi-byte wordwrap implementation
which also takes break length into consideration

Minimal multi - byte wordwrap implementation which also takes break length into consideration


private function generateColoursSetCode() : void
    {
        if (!ctype_digit($this->fg)) {
            $fgCode = self::$availableForegroundColors[$this->fg];
        } else {
            $fgCode = sprintf("38;5;%s", $this->fg);
        }

        if (!ctype_digit($this->bg)) {
            $bgCode = self::$availableBackgroundColors[$this->bg];
        } else {
            $bgCode = sprintf("48;5;%s", $this->bg);
        }

        $this->coloursSetCode = sprintf("\033[%s;%sm", $fgCode, $bgCode);
    }

private function generateColoursSetCode ( ) : void { if ( ! ctype_digit ( $ this -> fg ) ) { $ fgCode = self :: $ availableForegroundColors [ $ this -> fg ] ; } else { $ fgCode = sprintf ( "38;5;%s" , $ this -> fg ) ; } if ( ! ctype_digit ( $ this -> bg ) ) { $ bgCode = self :: $ availableBackgroundColors [ $ this -> bg ] ; } else { $ bgCode = sprintf ( "48;5;%s" , $ this -> bg ) ; } $ this -> coloursSetCode = sprintf ( "\033[%s;%sm" , $ fgCode , $ bgCode ) ; }

Generates the ansi escape sequence to set the colours


protected function calculateContentWidth() : void
    {
        $this->contentWidth = $this->width
            - ($this->paddingLeftRight * 2)
            - ($this->borderRightWidth + $this->borderLeftWidth);

        if ($this->contentWidth < 0) {
            $this->contentWidth = 0;
        }
    }

protected function calculateContentWidth ( ) : void { $ this -> contentWidth = $ this -> width - ( $ this -> paddingLeftRight * 2 ) - ( $ this -> borderRightWidth + $ this -> borderLeftWidth ) ; if ( $ this -> contentWidth < 0 ) { $ this -> contentWidth = 0 ; } }


public function getRightHandPadding(int $contentLength) : int
    {
        $rightPadding = $this->getContentWidth() - $contentLength + $this->getPaddingLeftRight();

        if ($rightPadding < 0) {
            $rightPadding = 0;
        }

        return $rightPadding;
    }

public function getRightHandPadding ( int $ contentLength ) : int { $ rightPadding = $ this -> getContentWidth ( ) - $ contentLength + $ this -> getPaddingLeftRight ( ) ; if ( $ rightPadding < 0 ) { $ rightPadding = 0 ; } return $ rightPadding ; }

Get padding for right had side of content


public function setBorder(
        int $topWidth,
        $rightWidth = null,
        $bottomWidth = null,
        $leftWidth = null,
        string $colour = null
    ) : self {
        if (!is_int($rightWidth)) {
            $colour = $rightWidth;
            $rightWidth = $bottomWidth = $leftWidth = $topWidth;
        } elseif (!is_int($bottomWidth)) {
            $colour = $bottomWidth;
            $bottomWidth = $topWidth;
            $leftWidth = $rightWidth;
        } elseif (!is_int($leftWidth)) {
            $colour = $leftWidth;
            $leftWidth = $rightWidth;
        }

        $this->borderTopWidth = $topWidth;
        $this->borderRightWidth = $rightWidth;
        $this->borderBottomWidth = $bottomWidth;
        $this->borderLeftWidth = $leftWidth;

        if (is_string($colour)) {
            $this->setBorderColour($colour);
        } elseif ($colour !== null) {
            throw new \InvalidArgumentException('Invalid colour');
        }

        $this->calculateContentWidth();
        $this->generateBorderRows();
        $this->generatePaddingTopBottomRows();

        return $this;
    }

public
function
setBorder
(
int
$
topWidth
,
$
rightWidth
=
,
$
bottomWidth
=
,
$
leftWidth
=
,
string
$
colour
=
)
:
self
{
if
(
!
is_int
(
$
rightWidth
)
)
{
$
colour
=
$
rightWidth
;
$
rightWidth
=
$
bottomWidth
=
$
leftWidth
=
$
topWidth
;
}
elseif
(
!
is_int
(
$
bottomWidth
)
)
{
$
colour
=
$
bottomWidth
;
$
bottomWidth
=
$
topWidth
;
$
leftWidth
=
$
rightWidth
;
}
elseif
(
!
is_int
(
$
leftWidth
)
)
{
$
colour
=
$
leftWidth
;
$
leftWidth
=
$
rightWidth
;
}
$
this
->
borderTopWidth
=
$
topWidth
;
$
this
->
borderRightWidth
=
$
rightWidth
;
$
this
->
borderBottomWidth
=
$
bottomWidth
;
$
this
->
borderLeftWidth
=
$
leftWidth
;
if
(
is_string
(
$
colour
)
)
{
$
this
->
setBorderColour
(
$
colour
)
;
}
elseif
(
$
colour
!==
)
{
throw
new
\
InvalidArgumentException
(
'Invalid colour'
)
;
}
$
this
->
calculateContentWidth
(
)
;
$
this
->
generateBorderRows
(
)
;
$
this
->
generatePaddingTopBottomRows
(
)
;
return
$
this
;
}

Shorthand function to set all borders values at once


public function display() : void
    {
        $this->assertMenuOpen();

        $this->terminal->moveCursorToRow($this->y);

        $this->emptyRow();

        $this->write(sprintf(
            "%s%s%s%s%s\n",
            $this->style->getColoursSetCode(),
            str_repeat(' ', $this->style->getPaddingLeftRight()),
            $this->text,
            str_repeat(' ', $this->style->getPaddingLeftRight()),
            $this->style->getColoursResetCode()
        ));

        $this->emptyRow();

        $this->terminal->moveCursorToTop();

        $reader = new NonCanonicalReader($this->terminal);
        $reader->readCharacter();

        $this->parentMenu->redraw();
    }

public
function
display
(
)
:
void
{
$
this
->
assertMenuOpen
(
)
;
$
this
->
terminal
->
moveCursorToRow
(
$
this
->
y
)
;
$
this
->
emptyRow
(
)
;
$
this
->
write
(
sprintf
(
"%s%s%s%s%s\n"
,
$
this
->
style
->
getColoursSetCode
(
)
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
$
this
->
text
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
$
this
->
style
->
getColoursResetCode
(
)
)
)
;
$
this
->
emptyRow
(
)
;
$
this
->
terminal
->
moveCursorToTop
(
)
;
$
reader
=
new
NonCanonicalReader
(
$
this
->
terminal
)
;
$
reader
->
readCharacter
(
)
;
$
this
->
parentMenu
->
redraw
(
)
;
}

Flash a message on top of the menu which
disappears on any keystroke.

Flash a message on top of the menu which disappears on any keystroke .


protected function calculateCoordinates() : void
    {
        //y
        $textLines = count(explode("\n", $this->text)) + 2;
        $this->y = (int) (ceil($this->parentMenu->getCurrentFrame()->count() / 2) - ceil($textLines / 2) + 1);

        //x
        $parentStyle = $this->parentMenu->getStyle();
        $dialogueHalfLength = (int) ((mb_strlen($this->text) + ($this->style->getPaddingLeftRight() * 2)) / 2);
        $widthHalfLength = (int) ceil($parentStyle->getWidth() / 2 + $parentStyle->getMargin());
        $this->x = $widthHalfLength - $dialogueHalfLength;
    }

protected function calculateCoordinates ( ) : void { //y $ textLines = count ( explode ( "\n" , $ this -> text ) ) + 2 ; $ this -> y = ( int ) ( ceil ( $ this -> parentMenu -> getCurrentFrame ( ) -> count ( ) / 2 ) - ceil ( $ textLines / 2 ) + 1 ) ; //x $ parentStyle = $ this -> parentMenu -> getStyle ( ) ; $ dialogueHalfLength = ( int ) ( ( mb_strlen ( $ this -> text ) + ( $ this -> style -> getPaddingLeftRight ( ) * 2 ) ) / 2 ) ; $ widthHalfLength = ( int ) ceil ( $ parentStyle -> getWidth ( ) / 2 + $ parentStyle -> getMargin ( ) ) ; $ this -> x = $ widthHalfLength - $ dialogueHalfLength ; }

Calculate the co-ordinates to write the messages

Calculate the co - ordinates to write the messages


protected function emptyRow() : void
    {
        $this->write(
            sprintf(
                "%s%s%s%s%s\n",
                $this->style->getColoursSetCode(),
                str_repeat(' ', $this->style->getPaddingLeftRight()),
                str_repeat(' ', mb_strlen($this->text)),
                str_repeat(' ', $this->style->getPaddingLeftRight()),
                $this->style->getColoursResetCode()
            )
        );
    }

protected
function
emptyRow
(
)
:
void
{
$
this
->
write
(
sprintf
(
"%s%s%s%s%s\n"
,
$
this
->
style
->
getColoursSetCode
(
)
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
str_repeat
(
' '
,
mb_strlen
(
$
this
->
text
)
)
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
$
this
->
style
->
getColoursResetCode
(
)
)
)
;
}


protected function write(string $text, int $column = null) : void
    {
        $this->terminal->moveCursorToColumn($column ?: $this->x);
        $this->terminal->write($text);
    }

protected function write ( string $ text , int $ column = null ) : void { $ this -> terminal -> moveCursorToColumn ( $ column ? : $ this -> x ) ; $ this -> terminal -> write ( $ text ) ; }


public function setText(string $text) : void
    {
        $this->text = implode("\n", array_map(function (string $line) {
            return rtrim($line, ' ');
        }, explode("\n", $text)));

        $this->calculateArtLength();
    }

public
function
setText
(
string
$
text
)
:
void
{
$
this
->
text
=
implode
(
"\n"
,
array_map
(
function
(
string
$
line
)
{
return
rtrim
(
$
line
,
' '
)
;
}
,
explode
(
"\n"
,
$
text
)
)
)
;
$
this
->
calculateArtLength
(
)
;
}


private function calculateArtLength() : void
    {
        $this->artLength = (int) max(array_map('mb_strlen', explode("\n", $this->text)));
    }

private function calculateArtLength ( ) : void { $ this -> artLength = ( int ) max ( array_map ( 'mb_strlen' , explode ( "\n" , $ this -> text ) ) ) ; }


public function display(string $confirmText = 'OK') : void
    {
        $this->assertMenuOpen();

        $this->terminal->moveCursorToRow($this->y);

        $promptWidth = mb_strlen($this->text) + 4;

        $this->emptyRow();

        $this->write(sprintf(
            "%s%s%s%s%s\n",
            $this->style->getColoursSetCode(),
            str_repeat(' ', $this->style->getPaddingLeftRight()),
            $this->text,
            str_repeat(' ', $this->style->getPaddingLeftRight()),
            $this->style->getColoursResetCode()
        ));

        $this->emptyRow();

        $confirmText = sprintf(' < %s > ', $confirmText);
        $leftFill    = (int) (($promptWidth / 2) - (mb_strlen($confirmText) / 2));

        $this->write(sprintf(
            "%s%s%s%s%s%s%s\n",
            $this->style->getColoursSetCode(),
            str_repeat(' ', $leftFill),
            $this->style->getInvertedColoursSetCode(),
            $confirmText,
            $this->style->getInvertedColoursUnsetCode(),
            str_repeat(' ', (int) ceil($promptWidth - $leftFill - mb_strlen($confirmText))),
            $this->style->getColoursResetCode()
        ));

        $this->write(sprintf(
            "%s%s%s%s%s\n",
            $this->style->getColoursSetCode(),
            str_repeat(' ', $this->style->getPaddingLeftRight()),
            str_repeat(' ', mb_strlen($this->text)),
            str_repeat(' ', $this->style->getPaddingLeftRight()),
            $this->style->getColoursResetCode()
        ));

        $this->terminal->moveCursorToTop();

        $reader = new NonCanonicalReader($this->terminal);

        while ($char = $reader->readCharacter()) {
            if ($char->isControl() && $char->getControl() === InputCharacter::ENTER) {
                $this->parentMenu->redraw();
                return;
            }
        }
    }

public
function
display
(
string
$
confirmText
=
'OK'
)
:
void
{
$
this
->
assertMenuOpen
(
)
;
$
this
->
terminal
->
moveCursorToRow
(
$
this
->
y
)
;
$
promptWidth
=
mb_strlen
(
$
this
->
text
)
+
4
;
$
this
->
emptyRow
(
)
;
$
this
->
write
(
sprintf
(
"%s%s%s%s%s\n"
,
$
this
->
style
->
getColoursSetCode
(
)
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
$
this
->
text
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
$
this
->
style
->
getColoursResetCode
(
)
)
)
;
$
this
->
emptyRow
(
)
;
$
confirmText
=
sprintf
(
' < %s > '
,
$
confirmText
)
;
$
leftFill
=
(
int
)
(
(
$
promptWidth
/
2
)
(
mb_strlen
(
$
confirmText
)
/
2
)
)
;
$
this
->
write
(
sprintf
(
"%s%s%s%s%s%s%s\n"
,
$
this
->
style
->
getColoursSetCode
(
)
,
str_repeat
(
' '
,
$
leftFill
)
,
$
this
->
style
->
getInvertedColoursSetCode
(
)
,
$
confirmText
,
$
this
->
style
->
getInvertedColoursUnsetCode
(
)
,
str_repeat
(
' '
,
(
int
)
ceil
(
$
promptWidth
$
leftFill
mb_strlen
(
$
confirmText
)
)
)
,
$
this
->
style
->
getColoursResetCode
(
)
)
)
;
$
this
->
write
(
sprintf
(
"%s%s%s%s%s\n"
,
$
this
->
style
->
getColoursSetCode
(
)
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
str_repeat
(
' '
,
mb_strlen
(
$
this
->
text
)
)
,
str_repeat
(
' '
,
$
this
->
style
->
getPaddingLeftRight
(
)
)
,
$
this
->
style
->
getColoursResetCode
(
)
)
)
;
$
this
->
terminal
->
moveCursorToTop
(
)
;
$
reader
=
new
NonCanonicalReader
(
$
this
->
terminal
)
;
while
(
$
char
=
$
reader
->
readCharacter
(
)
)
{
if
(
$
char
->
isControl
(
)
&&
$
char
->
getControl
(
)
===
InputCharacter
::
ENTER
)
{
$
this
->
parentMenu
->
redraw
(
)
;
return
;
}
}
}

Display confirmation with a button with the given text


public function connection(string $name = null): Client
    {
        $name = $name ?: $this->getDefaultConnection();

        if (!isset($this->connections[$name])) {
            $client = $this->makeConnection($name);

            $this->connections[$name] = $client;
        }

        return $this->connections[$name];
    }

public function connection ( string $ name = null ) : Client { $ name = $ name ? : $ this -> getDefaultConnection ( ) ; if ( ! isset ( $ this -> connections [ $ name ] ) ) { $ client = $ this -> makeConnection ( $ name ) ; $ this -> connections [ $ name ] = $ client ; } return $ this -> connections [ $ name ] ; }

Retrieve or build the named connection.

@param string|null $name

@return Client

Retrieve or build the named connection .


protected function makeConnection(string $name): Client
    {
        $config = $this->getConfig($name);

        return $this->factory->make($config);
    }

protected function makeConnection ( string $ name ) : Client { $ config = $ this -> getConfig ( $ name ) ; return $ this -> factory -> make ( $ config ) ; }

Make a new connection.

@param string $name

@return \Elasticsearch\Client


protected function getConfig(string $name)
    {
        $connections = $this->app['config']['elasticsearch.connections'];

        if (null === $config = array_get($connections, $name)) {
            throw new \InvalidArgumentException("Elasticsearch connection [$name] not configured.");
        }

        return $config;
    }

Get the configuration for a named connection.

@param $name

@return mixed
@throws \InvalidArgumentException

Get the configuration for a named connection .


public function Compress(&$curl_headers, &$requestBody)
    {
        if (!function_exists('gzencode')) {
            return;
        }

        $requestBody = gzencode($requestBody);

        $curl_headers['content-encoding']='deflate';
        $curl_headers['content-length']=strlen($requestBody);
    }

public function Compress ( & $ curl_headers , & $ requestBody ) { if ( ! function_exists ( 'gzencode' ) ) { return ; } $ requestBody = gzencode ( $ requestBody ) ; $ curl_headers [ 'content-encoding' ] = 'deflate' ; $ curl_headers [ 'content-length' ] = strlen ( $ requestBody ) ; }

Compresses the input byte array into stream.
@param curl_headers Curl headers, pre-compression
@param requestBody POST body, pre-compression

Compresses the input byte array into stream .


public function __isset($key)
    {
        $this->parse();
        if (isset($this->_ruleMap[$key])) {
            $key = $this->_ruleMap[$key];
            return isset($this->_options[$key]);
        }
        return false;
    }

public function __isset ( $ key ) { $ this -> parse ( ) ; if ( isset ( $ this -> _ruleMap [ $ key ] ) ) { $ key = $ this -> _ruleMap [ $ key ] ; return isset ( $ this -> _options [ $ key ] ) ; } return false ; }

Test whether a given option has been seen.

@param  string $key
@return boolean

Test whether a given option has been seen .


public function addArguments($argv)
    {
        if (!is_array($argv)) {
            require_once 'Zend/Console/Getopt/Exception.php';
            throw new Zend_Console_Getopt_Exception(
                "Parameter #1 to addArguments should be an array");
        }
        $this->_argv = array_merge($this->_argv, $argv);
        $this->_parsed = false;
        return $this;
    }

Define additional command-line arguments.
These are appended to those defined when the constructor was called.

@param  array $argv
@throws Zend_Console_Getopt_Exception When not given an array as parameter
@return Zend_Console_Getopt Provides a fluent interface

Define additional command - line arguments . These are appended to those defined when the constructor was called .


public function setArguments($argv)
    {
        if (!is_array($argv)) {
            require_once 'Zend/Console/Getopt/Exception.php';
            throw new Zend_Console_Getopt_Exception(
                "Parameter #1 to setArguments should be an array");
        }
        $this->_argv = $argv;
        $this->_parsed = false;
        return $this;
    }

Define full set of command-line arguments.
These replace any currently defined.

@param  array $argv
@throws Zend_Console_Getopt_Exception When not given an array as parameter
@return Zend_Console_Getopt Provides a fluent interface

Define full set of command - line arguments . These replace any currently defined .


public function setOptions($getoptConfig)
    {
        if (isset($getoptConfig)) {
            foreach ($getoptConfig as $key => $value) {
                $this->setOption($key, $value);
            }
        }
        return $this;
    }

public function setOptions ( $ getoptConfig ) { if ( isset ( $ getoptConfig ) ) { foreach ( $ getoptConfig as $ key => $ value ) { $ this -> setOption ( $ key , $ value ) ; } } return $ this ; }

Define multiple configuration options from an associative array.
These are not program options, but properties to configure
the behavior of Zend_Console_Getopt.

@param  array $getoptConfig
@return Zend_Console_Getopt Provides a fluent interface

Define multiple configuration options from an associative array . These are not program options but properties to configure the behavior of Zend_Console_Getopt .


public function addRules($rules)
    {
        $ruleMode = $this->_getoptConfig['ruleMode'];
        switch ($this->_getoptConfig['ruleMode']) {
            case self::MODE_ZEND:
                if (is_array($rules)) {
                    $this->_addRulesModeZend($rules);
                    break;
                }
                // intentional fallthrough
            case self::MODE_GNU:
                $this->_addRulesModeGnu($rules);
                break;
            default:
                /**
                 * Call addRulesModeFoo() for ruleMode 'foo'.
                 * The developer should subclass Getopt and
                 * provide this method.
                 */
                $method = '_addRulesMode' . ucfirst($ruleMode);
                $this->$method($rules);
        }
        $this->_parsed = false;
        return $this;
    }

Define additional option rules.
These are appended to the rules defined when the constructor was called.

@param  array $rules
@return Zend_Console_Getopt Provides a fluent interface

Define additional option rules . These are appended to the rules defined when the constructor was called .


public function toString()
    {
        $this->parse();
        $s = array();
        foreach ($this->_options as $flag => $value) {
            $s[] = $flag . '=' . ($value === true ? 'true' : $value);
        }
        return implode(' ', $s);
    }

public
function
toString
(
)
{
$
this
->
parse
(
)
;
$
s
=
array
(
)
;
foreach
(
$
this
->
_options
as
$
flag
=>
$
value
)
{
$
s
[
]
=
$
flag
.
'='
.
(
$
value
===
true
'true'
:
$
value
)
;
}
return
implode
(
' '
,
$
s
)
;
}

Return the current set of options and parameters seen as a string.

@return string

Return the current set of options and parameters seen as a string .


public function toArray()
    {
        $this->parse();
        $s = array();
        foreach ($this->_options as $flag => $value) {
            $s[] = $flag;
            if ($value !== true) {
                $s[] = $value;
            }
        }
        return $s;
    }

public function toArray ( ) { $ this -> parse ( ) ; $ s = array ( ) ; foreach ( $ this -> _options as $ flag => $ value ) { $ s [ ] = $ flag ; if ( $ value !== true ) { $ s [ ] = $ value ; } } return $ s ; }

Return the current set of options and parameters seen
as an array of canonical options and parameters.

Clusters have been expanded, and option aliases
have been mapped to their primary option names.

@return array

Return the current set of options and parameters seen as an array of canonical options and parameters .


public function toJson()
    {
        $this->parse();
        $j = array();
        foreach ($this->_options as $flag => $value) {
            $j['options'][] = array(
                'option' => array(
                    'flag' => $flag,
                    'parameter' => $value
                )
            );
        }

        /**
         * @see Zend_Json
         */
        require_once 'Zend/Json.php';
        $json = Zend_Json::encode($j);

        return $json;
    }

/**
         * @see Zend_Json
         */

Return the current set of options and parameters seen in Json format.

@return string

Return the current set of options and parameters seen in Json format .


public function toXml()
    {
        $this->parse();
        $doc = new DomDocument('1.0', 'utf-8');
        $optionsNode = $doc->createElement('options');
        $doc->appendChild($optionsNode);
        foreach ($this->_options as $flag => $value) {
            $optionNode = $doc->createElement('option');
            $optionNode->setAttribute('flag', utf8_encode($flag));
            if ($value !== true) {
                $optionNode->setAttribute('parameter', utf8_encode($value));
            }
            $optionsNode->appendChild($optionNode);
        }
        $xml = $doc->saveXML();
        return $xml;
    }

public function toXml ( ) { $ this -> parse ( ) ; $ doc = new DomDocument ( '1.0' , 'utf-8' ) ; $ optionsNode = $ doc -> createElement ( 'options' ) ; $ doc -> appendChild ( $ optionsNode ) ; foreach ( $ this -> _options as $ flag => $ value ) { $ optionNode = $ doc -> createElement ( 'option' ) ; $ optionNode -> setAttribute ( 'flag' , utf8_encode ( $ flag ) ) ; if ( $ value !== true ) { $ optionNode -> setAttribute ( 'parameter' , utf8_encode ( $ value ) ) ; } $ optionsNode -> appendChild ( $ optionNode ) ; } $ xml = $ doc -> saveXML ( ) ; return $ xml ; }

Return the current set of options and parameters seen in XML format.

@return string

Return the current set of options and parameters seen in XML format .


public function getOption($flag)
    {
        $this->parse();
        if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
            $flag = strtolower($flag);
        }
        if (isset($this->_ruleMap[$flag])) {
            $flag = $this->_ruleMap[$flag];
            if (isset($this->_options[$flag])) {
                return $this->_options[$flag];
            }
        }
        return null;
    }

public function getOption ( $ flag ) { $ this -> parse ( ) ; if ( $ this -> _getoptConfig [ self :: CONFIG_IGNORECASE ] ) { $ flag = strtolower ( $ flag ) ; } if ( isset ( $ this -> _ruleMap [ $ flag ] ) ) { $ flag = $ this -> _ruleMap [ $ flag ] ; if ( isset ( $ this -> _options [ $ flag ] ) ) { return $ this -> _options [ $ flag ] ; } } return null ; }

Return the state of the option seen on the command line of the
current application invocation.

This function returns true, or the parameter value to the option, if any.
If the option was not given, this function returns false.

@param  string $flag
@return mixed

Return the state of the option seen on the command line of the current application invocation .


public function getUsageMessage()
    {
        $usage = "Usage: {$this->_progname} [ options ]\n";
        $maxLen = 20;
        $lines = array();
        foreach ($this->_rules as $rule) {
            $flags = array();
            if (is_array($rule['alias'])) {
                foreach ($rule['alias'] as $flag) {
                    $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag;
                }
            }
            $linepart['name'] = implode('|', $flags);
            if (isset($rule['param']) && $rule['param'] != 'none') {
                $linepart['name'] .= ' ';
                switch ($rule['param']) {
                    case 'optional':
                        $linepart['name'] .= "[ <{$rule['paramType']}> ]";
                        break;
                    case 'required':
                        $linepart['name'] .= "<{$rule['paramType']}>";
                        break;
                }
            }
            if (strlen($linepart['name']) > $maxLen) {
                $maxLen = strlen($linepart['name']);
            }
            $linepart['help'] = '';
            if (isset($rule['help'])) {
                $linepart['help'] .= $rule['help'];
            }
            $lines[] = $linepart;
        }
        foreach ($lines as $linepart) {
            $usage .= sprintf("%s %s\n",
            str_pad($linepart['name'], $maxLen),
            $linepart['help']);
        }
        return $usage;
    }

Return a useful option reference, formatted for display in an
error message.

Note that this usage information is provided in most Exceptions
generated by this class.

@return string

Return a useful option reference formatted for display in an error message .


public function setAliases($aliasMap)
    {
        foreach ($aliasMap as $flag => $alias) {
            if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
                $flag = strtolower($flag);
                $alias = strtolower($alias);
            }
            if (!isset($this->_ruleMap[$flag])) {
                continue;
            }
            $flag = $this->_ruleMap[$flag];
            if (isset($this->_rules[$alias]) || isset($this->_ruleMap[$alias])) {
                $o = (strlen($alias) == 1 ? '-' : '--') . $alias;
                require_once 'Zend/Console/Getopt/Exception.php';
                throw new Zend_Console_Getopt_Exception(
                    "Option \"$o\" is being defined more than once.");
            }
            $this->_rules[$flag]['alias'][] = $alias;
            $this->_ruleMap[$alias] = $flag;
        }
        return $this;
    }

Define aliases for options.

The parameter $aliasMap is an associative array
mapping option name (short or long) to an alias.

@param  array $aliasMap
@throws Zend_Console_Getopt_Exception
@return Zend_Console_Getopt Provides a fluent interface


public function setHelp($helpMap)
    {
        foreach ($helpMap as $flag => $help) {
            if (!isset($this->_ruleMap[$flag])) {
                continue;
            }
            $flag = $this->_ruleMap[$flag];
            $this->_rules[$flag]['help'] = $help;
        }
        return $this;
    }

public function setHelp ( $ helpMap ) { foreach ( $ helpMap as $ flag => $ help ) { if ( ! isset ( $ this -> _ruleMap [ $ flag ] ) ) { continue ; } $ flag = $ this -> _ruleMap [ $ flag ] ; $ this -> _rules [ $ flag ] [ 'help' ] = $ help ; } return $ this ; }

Define help messages for options.

The parameter $help_map is an associative array
mapping option name (short or long) to the help string.

@param  array $helpMap
@return Zend_Console_Getopt Provides a fluent interface


public function parse()
    {
        if ($this->_parsed === true) {
            return;
        }
        $argv = $this->_argv;
        $this->_options = array();
        $this->_remainingArgs = array();
        while (count($argv) > 0) {
            if ($argv[0] == '--') {
                array_shift($argv);
                if ($this->_getoptConfig[self::CONFIG_DASHDASH]) {
                    $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
                    break;
                }
            }
            if (substr($argv[0], 0, 2) == '--') {
                $this->_parseLongOption($argv);
            } elseif (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) {
                $this->_parseShortOptionCluster($argv);
            } elseif ($this->_getoptConfig[self::CONFIG_PARSEALL]) {
                $this->_remainingArgs[] = array_shift($argv);
            } else {
                /*
                 * We should put all other arguments in _remainingArgs and stop parsing
                 * since CONFIG_PARSEALL is false.
                 */
                $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
                break;
            }
        }
        $this->_parsed = true;
        return $this;
    }

Parse command-line arguments and find both long and short
options.

Also find option parameters, and remaining arguments after
all options have been parsed.

@return Zend_Console_Getopt|null Provides a fluent interface

Parse command - line arguments and find both long and short options .


protected function _parseShortOptionCluster(&$argv)
    {
        $flagCluster = ltrim(array_shift($argv), '-');
        foreach (str_split($flagCluster) as $flag) {
            $this->_parseSingleOption($flag, $argv);
        }
    }

protected function _parseShortOptionCluster ( & $ argv ) { $ flagCluster = ltrim ( array_shift ( $ argv ) , '-' ) ; foreach ( str_split ( $ flagCluster ) as $ flag ) { $ this -> _parseSingleOption ( $ flag , $ argv ) ; } }

Parse command-line arguments for short options.
Short options are those preceded by a single '-' character.
Short options may be clustered.

@param  mixed &$argv
@return void

Parse command - line arguments for short options . Short options are those preceded by a single - character . Short options may be clustered .


protected function _parseSingleOption($flag, &$argv)
    {
        if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
            $flag = strtolower($flag);
        }
        if (!isset($this->_ruleMap[$flag])) {
            require_once 'Zend/Console/Getopt/Exception.php';
            throw new Zend_Console_Getopt_Exception(
                "Option \"$flag\" is not recognized.",
                $this->getUsageMessage());
        }
        $realFlag = $this->_ruleMap[$flag];
        switch ($this->_rules[$realFlag]['param']) {
            case 'required':
                if (count($argv) > 0) {
                    $param = array_shift($argv);
                    $this->_checkParameterType($realFlag, $param);
                } else {
                    require_once 'Zend/Console/Getopt/Exception.php';
                    throw new Zend_Console_Getopt_Exception(
                        "Option \"$flag\" requires a parameter.",
                        $this->getUsageMessage());
                }
                break;
            case 'optional':
                if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
                    $param = array_shift($argv);
                    $this->_checkParameterType($realFlag, $param);
                } else {
                    $param = true;
                }
                break;
            default:
                $param = true;
        }
        $this->_options[$realFlag] = $param;
    }

Parse command-line arguments for a single option.

@param  string $flag
@param  mixed  $argv
@throws Zend_Console_Getopt_Exception
@return void

Parse command - line arguments for a single option .


protected function _addRulesModeGnu($rules)
    {
        $ruleArray = array();

        /**
         * Options may be single alphanumeric characters.
         * Options may have a ':' which indicates a required string parameter.
         * No long options or option aliases are supported in GNU style.
         */
        preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
        foreach ($ruleArray[1] as $rule) {
            $r = array();
            $flag = substr($rule, 0, 1);
            if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
                $flag = strtolower($flag);
            }
            $r['alias'][] = $flag;
            if (substr($rule, 1, 1) == ':') {
                $r['param'] = 'required';
                $r['paramType'] = 'string';
            } else {
                $r['param'] = 'none';
            }
            $this->_rules[$flag] = $r;
            $this->_ruleMap[$flag] = $flag;
        }
    }

Define legal options using the gnu-style format.

@param  string $rules
@return void

Define legal options using the gnu - style format .


protected function _addRulesModeZend($rules)
    {
        foreach ($rules as $ruleCode => $helpMessage) {
            // this may have to translate the long parm type if there
            // are any complaints that =string will not work (even though that use
            // case is not documented)
            if (in_array(substr($ruleCode, -2, 1), array('-', '='))) {
                $flagList  = substr($ruleCode, 0, -2);
                $delimiter = substr($ruleCode, -2, 1);
                $paramType = substr($ruleCode, -1);
            } else {
                $flagList = $ruleCode;
                $delimiter = $paramType = null;
            }
            if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
                $flagList = strtolower($flagList);
            }
            $flags = explode('|', $flagList);
            $rule = array();
            $mainFlag = $flags[0];
            foreach ($flags as $flag) {
                if (empty($flag)) {
                    require_once 'Zend/Console/Getopt/Exception.php';
                    throw new Zend_Console_Getopt_Exception(
                        "Blank flag not allowed in rule \"$ruleCode\".");
                }
                if (strlen($flag) == 1) {
                    if (isset($this->_ruleMap[$flag])) {
                        require_once 'Zend/Console/Getopt/Exception.php';
                        throw new Zend_Console_Getopt_Exception(
                            "Option \"-$flag\" is being defined more than once.");
                    }
                    $this->_ruleMap[$flag] = $mainFlag;
                    $rule['alias'][] = $flag;
                } else {
                    if (isset($this->_rules[$flag]) || isset($this->_ruleMap[$flag])) {
                        require_once 'Zend/Console/Getopt/Exception.php';
                        throw new Zend_Console_Getopt_Exception(
                            "Option \"--$flag\" is being defined more than once.");
                    }
                    $this->_ruleMap[$flag] = $mainFlag;
                    $rule['alias'][] = $flag;
                }
            }
            if (isset($delimiter)) {
                switch ($delimiter) {
                    case self::PARAM_REQUIRED:
                        $rule['param'] = 'required';
                        break;
                    case self::PARAM_OPTIONAL:
                    default:
                        $rule['param'] = 'optional';
                }
                switch (substr($paramType, 0, 1)) {
                    case self::TYPE_WORD:
                        $rule['paramType'] = 'word';
                        break;
                    case self::TYPE_INTEGER:
                        $rule['paramType'] = 'integer';
                        break;
                    case self::TYPE_STRING:
                    default:
                        $rule['paramType'] = 'string';
                }
            } else {
                $rule['param'] = 'none';
            }
            $rule['help'] = $helpMessage;
            $this->_rules[$mainFlag] = $rule;
        }
    }

Define legal options using the Zend-style format.

@param  array $rules
@throws Zend_Console_Getopt_Exception
@return void

Define legal options using the Zend - style format .


public function getOAuthHeader($uri, $queryParameters, $httpMethod){
      $this->sign($uri, $queryParameters, $httpMethod);
      foreach($this->oauthParameters as $k => $v){
           $this->oauthParameters[$k] = $k . '="' . rawurlencode($v) . '"';
      }
      return 'OAuth ' . implode(',', $this->oauthParameters);
  }

public
function
getOAuthHeader
(
$
uri
,
$
queryParameters
,
$
httpMethod
)
{
$
this
->
sign
(
$
uri
,
$
queryParameters
,
$
httpMethod
)
;
foreach
(
$
this
->
oauthParameters
as
$
k
=>
$
v
)
{
$
this
->
oauthParameters
[
$
k
]
=
$
k
.
'="'
.
rawurlencode
(
$
v
)
.
'"'
;
}
return
'OAuth '
.
implode
(
','
,
$
this
->
oauthParameters
)
;
}

Return the completed signed Authorization Header
@param String $uri              The complete URL contains everything
@param Array $queryParameters   The QueryParaemters for the request
@param String $httpMethod       The Http Method. POST or GET
@return String Authorization Header


public function getBaseString($uri, $method, array $parameters = array()){
      $baseString = $this->prepareHttpMethod($method) . '&' .
                    $this->prepareURL($uri) . '&' .
                    $this->prepareQueryParams($parameters);
      return $baseString;
  }

public function getBaseString ( $ uri , $ method , array $ parameters = array ( ) ) { $ baseString = $ this -> prepareHttpMethod ( $ method ) . '&' . $ this -> prepareURL ( $ uri ) . '&' . $ this -> prepareQueryParams ( $ parameters ) ; return $ baseString ; }

Prepare the base String for OAuth 1 to sign
@param String $uri                 The Complete URL contains everything
@param String $method              The Http Method. POST or GET
@param Array $parameters           The query parameters for the array
@return String   The baseString for sign


private function prepareHttpMethod($method){
       $trimmedMethod = trim($method);
       $upperMethod = strtoupper($trimmedMethod);
       return rawurlencode($method);
  }

private function prepareHttpMethod ( $ method ) { $ trimmedMethod = trim ( $ method ) ; $ upperMethod = strtoupper ( $ trimmedMethod ) ; return rawurlencode ( $ method ) ; }

Helper method to format the HTTP method
@param String $method    The Post or Get
@return String    The formatted HTTP method


private function setNonce($length = 6){
        $result = '';
        $cLength = strlen(self::NONCE_CHARS);
        for ($i=0; $i < $length; $i++)
        {
           $rnum = rand(0,$cLength - 1);
           $result .= substr(self::NONCE_CHARS,$rnum,1);
        }
        $this->oauthNonce = $result;
  }

private function setNonce ( $ length = 6 ) { $ result = '' ; $ cLength = strlen ( self :: NONCE_CHARS ) ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ rnum = rand ( 0 , $ cLength - 1 ) ; $ result .= substr ( self :: NONCE_CHARS , $ rnum , 1 ) ; } $ this -> oauthNonce = $ result ; }

Set a random nonce for the signature
@param int $length   the lenght of the lenght


private function appendOAuthPartsTo(array $queryParameters = null){
      if($queryParameters == null){
          $queryParameters = array();
      }
      $queryParameters['oauth_consumer_key'] = $this->consumerKey;
      $queryParameters['oauth_token'] = $this->oauthToken;
      $queryParameters['oauth_signature_method'] ='HMAC-SHA1';
      $queryParameters['oauth_timestamp'] = $this->oauthTimeStamp;
      $queryParameters['oauth_nonce'] =$this->oauthNonce;
      $queryParameters['oauth_version'] = '1.0';
      return $queryParameters;
  }

private function appendOAuthPartsTo ( array $ queryParameters = null ) { if ( $ queryParameters == null ) { $ queryParameters = array ( ) ; } $ queryParameters [ 'oauth_consumer_key' ] = $ this -> consumerKey ; $ queryParameters [ 'oauth_token' ] = $ this -> oauthToken ; $ queryParameters [ 'oauth_signature_method' ] = 'HMAC-SHA1' ; $ queryParameters [ 'oauth_timestamp' ] = $ this -> oauthTimeStamp ; $ queryParameters [ 'oauth_nonce' ] = $ this -> oauthNonce ; $ queryParameters [ 'oauth_version' ] = '1.0' ; return $ queryParameters ; }

Add all OAuth query paraemters to the signature string string
@param Array $queryParameters    The queryParameters to be included
@return Array $queryParameters   The complete query parameters


public function getString()
    {
        if (empty($this->sql) || empty($this->entity)) {
            return null;
        }

        $query = "";
        $query .= $this->sql;

        if (0==count($this->projection)) {
            $query .= " "."*";
        } else {
            if (count($this->projection)) {
                $query .= " " . implode(", ", $this->projection);
            }
        }

        $query .= " FROM " . $this->entity;

        if (!empty($this->whereClause)) {
            if (count($this->whereClause)) {
                $query .= " WHERE " . implode(" AND ", $this->whereClause);
            }
        }

        if (!empty($this->orderByClause)) {
            $query .= " ORDERBY " . $this->orderByClause;
        }

        if (!empty($this->startposition)) {
            $query .= " STARTPOSITION " . $this->startposition;
        }

        if (!empty($this->maxresults)) {
            $query .= " MAXRESULTS " . $this->maxresults;
        }

        return $query;
    }

public
function
getString
(
)
{
if
(
empty
(
$
this
->
sql
)
||
empty
(
$
this
->
entity
)
)
{
return
;
}
$
query
=
""
;
$
query
.=
$
this
->
sql
;
if
(
0
==
count
(
$
this
->
projection
)
)
{
$
query
.=
" "
.
"*"
;
}
else
{
if
(
count
(
$
this
->
projection
)
)
{
$
query
.=
" "
.
implode
(
", "
,
$
this
->
projection
)
;
}
}
$
query
.=
" FROM "
.
$
this
->
entity
;
if
(
!
empty
(
$
this
->
whereClause
)
)
{
if
(
count
(
$
this
->
whereClause
)
)
{
$
query
.=
" WHERE "
.
implode
(
" AND "
,
$
this
->
whereClause
)
;
}
}
if
(
!
empty
(
$
this
->
orderByClause
)
)
{
$
query
.=
" ORDERBY "
.
$
this
->
orderByClause
;
}
if
(
!
empty
(
$
this
->
startposition
)
)
{
$
query
.=
" STARTPOSITION "
.
$
this
->
startposition
;
}
if
(
!
empty
(
$
this
->
maxresults
)
)
{
$
query
.=
" MAXRESULTS "
.
$
this
->
maxresults
;
}
return
$
query
;
}

Get SQL query specified by object's members
@return string query

Get SQL query specified by object s members


public static function createClient($clientName = CoreConstants::CLIENT_CURL){
      if($clientName == CoreConstants::CLIENT_CURL){
         if(extension_loaded('curl')){
            return new CurlHttpClient();
         }else{
            throw new SdkException("curl extension is not enabled. Cannot create curl http client for the SDK.");
         }
      }

      if(strcasecmp($clientName, CoreConstants::CLIENT_GUZZLE) == 0 ||strcasecmp($clientName, CoreConstants::CLIENT_GUZZLE_FULL) == 0){
          if(class_exists('GuzzleHttp\Client')){
             return new GuzzleHttpClient();
          }else{
            throw new SdkException("guzzle client cannot be found. Cannot create guzzle http client for the SDK.");
          }
      }

      throw new SdkException("The client Name you passed is not supported. Please use either 'curl' or 'guzzle' for the client Name.");
  }

A static factory to create Http Client.
@param String HttpClient Name, default is using curl. Developer can set guzzleclient by passing 'guzzle' as client Name
@return HttpClientInterface

A static factory to create Http Client .


public function GetLogDestination()
    {
        if ($this->EnableServiceRequestsLogging) {
            if (false === file_exists($this->ServiceRequestLoggingLocation)) {
                $this->ServiceRequestLoggingLocation = sys_get_temp_dir();
            }
        }
        return $this->ServiceRequestLoggingLocation;
    }

public function GetLogDestination ( ) { if ( $ this -> EnableServiceRequestsLogging ) { if ( false === file_exists ( $ this -> ServiceRequestLoggingLocation ) ) { $ this -> ServiceRequestLoggingLocation = sys_get_temp_dir ( ) ; } } return $ this -> ServiceRequestLoggingLocation ; }

Gets the log destination folder
@return string log destination folder