code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
protected function getDumpers() { ksort($this->dumpers); return implode(', ', array_keys($this->dumpers)); }
Returns the list of available dumpers sorted by alphabetical order. @return string The list of available dumpers comma separated.
getDumpers
php
thephpleague/geotools
src/CLI/Command/Geocoder/Command.php
https://github.com/thephpleague/geotools/blob/master/src/CLI/Command/Geocoder/Command.php
MIT
public function initialBearing() { Ellipsoid::checkCoordinatesEllipsoid($this->from, $this->to); $latA = deg2rad($this->from->getLatitude()); $latB = deg2rad($this->to->getLatitude()); $dLng = deg2rad($this->to->getLongitude() - $this->from->getLongitude()); $y = sin($dLng) * cos($latB); $x = cos($latA) * sin($latB) - sin($latA) * cos($latB) * cos($dLng); return fmod(rad2deg(atan2($y, $x)) + 360, 360); }
Returns the initial bearing from the origin coordinate to the destination coordinate in degrees. @return float The initial bearing in degrees
initialBearing
php
thephpleague/geotools
src/Vertex/Vertex.php
https://github.com/thephpleague/geotools/blob/master/src/Vertex/Vertex.php
MIT
public function finalBearing() { Ellipsoid::checkCoordinatesEllipsoid($this->from, $this->to); $latA = deg2rad($this->to->getLatitude()); $latB = deg2rad($this->from->getLatitude()); $dLng = deg2rad($this->from->getLongitude() - $this->to->getLongitude()); $y = sin($dLng) * cos($latB); $x = cos($latA) * sin($latB) - sin($latA) * cos($latB) * cos($dLng); return fmod(fmod(rad2deg(atan2($y, $x)) + 360, 360) + 180, 360); }
Returns the final bearing from the origin coordinate to the destination coordinate in degrees. @return float The final bearing in degrees
finalBearing
php
thephpleague/geotools
src/Vertex/Vertex.php
https://github.com/thephpleague/geotools/blob/master/src/Vertex/Vertex.php
MIT
public function initialCardinal() { Ellipsoid::checkCoordinatesEllipsoid($this->from, $this->to); return Geotools::$cardinalPoints[(integer) round($this->initialBearing() / 22.5)]; }
Returns the initial cardinal point / direction from the origin coordinate to the destination coordinate. @see http://en.wikipedia.org/wiki/Cardinal_direction @return string The initial cardinal point / direction
initialCardinal
php
thephpleague/geotools
src/Vertex/Vertex.php
https://github.com/thephpleague/geotools/blob/master/src/Vertex/Vertex.php
MIT
public function finalCardinal() { Ellipsoid::checkCoordinatesEllipsoid($this->from, $this->to); return Geotools::$cardinalPoints[(integer) round($this->finalBearing() / 22.5)]; }
Returns the final cardinal point / direction from the origin coordinate to the destination coordinate. @see http://en.wikipedia.org/wiki/Cardinal_direction @return string The final cardinal point / direction
finalCardinal
php
thephpleague/geotools
src/Vertex/Vertex.php
https://github.com/thephpleague/geotools/blob/master/src/Vertex/Vertex.php
MIT
public function middle() { Ellipsoid::checkCoordinatesEllipsoid($this->from, $this->to); $latA = deg2rad($this->from->getLatitude()); $lngA = deg2rad($this->from->getLongitude()); $latB = deg2rad($this->to->getLatitude()); $lngB = deg2rad($this->to->getLongitude()); $bx = cos($latB) * cos($lngB - $lngA); $by = cos($latB) * sin($lngB - $lngA); $lat3 = rad2deg(atan2(sin($latA) + sin($latB), sqrt((cos($latA) + $bx) * (cos($latA) + $bx) + $by * $by))); $lng3 = rad2deg($lngA + atan2($by, cos($latA) + $bx)); return new Coordinate([$lat3, $lng3], $this->from->getEllipsoid()); }
Returns the half-way point / coordinate along a great circle path between the origin and the destination coordinates. @return CoordinateInterface
middle
php
thephpleague/geotools
src/Vertex/Vertex.php
https://github.com/thephpleague/geotools/blob/master/src/Vertex/Vertex.php
MIT
public function destination($bearing, $distance) { $lat = deg2rad($this->from->getLatitude()); $lng = deg2rad($this->from->getLongitude()); $bearing = deg2rad($bearing); $endLat = asin(sin($lat) * cos($distance / $this->from->getEllipsoid()->getA()) + cos($lat) * sin($distance / $this->from->getEllipsoid()->getA()) * cos($bearing)); $endLon = $lng + atan2(sin($bearing) * sin($distance / $this->from->getEllipsoid()->getA()) * cos($lat), cos($distance / $this->from->getEllipsoid()->getA()) - sin($lat) * sin($endLat)); return new Coordinate([rad2deg($endLat), rad2deg($endLon)], $this->from->getEllipsoid()); }
Returns the destination point with a given bearing in degrees travelling along a (shortest distance) great circle arc and a distance in meters. @param integer $bearing The bearing of the origin in degrees. @param integer $distance The distance from the origin in meters. @return CoordinateInterface
destination
php
thephpleague/geotools
src/Vertex/Vertex.php
https://github.com/thephpleague/geotools/blob/master/src/Vertex/Vertex.php
MIT
public function getOtherCoordinate(CoordinateInterface $coordinate) { if ($coordinate->isEqual($this->from)) { return $this->to; } else if ($coordinate->isEqual($this->to)) { return $this->from; } return null; }
Returns the other coordinate who is not the coordinate passed on argument @param CoordinateInterface $coordinate @return null|Coordinate
getOtherCoordinate
php
thephpleague/geotools
src/Vertex/Vertex.php
https://github.com/thephpleague/geotools/blob/master/src/Vertex/Vertex.php
MIT
public function getDeterminant(Vertex $vertex) { $abscissaVertexOne = $this->to->getLatitude() - $this->from->getLatitude(); $ordinateVertexOne = $this->to->getLongitude() - $this->from->getLongitude(); $abscissaVertexSecond = $vertex->getTo()->getLatitude() - $vertex->getFrom()->getLatitude(); $ordinateVertexSecond = $vertex->getTo()->getLongitude() - $vertex->getFrom()->getLongitude(); return bcsub( bcmul($abscissaVertexOne, $ordinateVertexSecond, $this->precision), bcmul($abscissaVertexSecond, $ordinateVertexOne, $this->precision), $this->precision ); }
Returns the determinant value between $this (vertex) and another vertex. @param Vertex $vertex [description] @return [type] [description]
getDeterminant
php
thephpleague/geotools
src/Vertex/Vertex.php
https://github.com/thephpleague/geotools/blob/master/src/Vertex/Vertex.php
MIT
protected function createAddress(array $data) { return Address::createFromArray($data); }
Create an address object for testing @param array $data @return Address|null
createAddress
php
thephpleague/geotools
tests/TestCase.php
https://github.com/thephpleague/geotools/blob/master/tests/TestCase.php
MIT
protected function createEmptyAddress() { return $this->createAddress([]); }
Create an empty address object @return Address|null
createEmptyAddress
php
thephpleague/geotools
tests/TestCase.php
https://github.com/thephpleague/geotools/blob/master/tests/TestCase.php
MIT
public function start() { // initialize the current scene $this->currentScene->load(); // start the game loop $this->container->resolveGameLoopMain()->start(); }
Start the game This will begin the game loop
start
php
phpgl/flappyphpant
src/Game.php
https://github.com/phpgl/flappyphpant/blob/master/src/Game.php
MIT
public function __debugInfo() { return ['currentScene' => $this->currentScene->getName()]; }
Custom debug info. I know, I know, there should't be references to game in the first place..
__debugInfo
php
phpgl/flappyphpant
src/Game.php
https://github.com/phpgl/flappyphpant/blob/master/src/Game.php
MIT
public function __construct( protected GameContainer $container, ) { parent::__construct($container); // basic camera system $this->cameraSystem = new CameraSystem2D( $this->container->resolveInput(), $this->container->resolveVisuDispatcher(), $this->container->resolveInputContext(), ); // basic rendering system $this->renderingSystem = new RenderingSystem2D( $this->container->resolveGL(), $this->container->resolveShaders() ); // the thing moving the flying phpants $this->visuPhpantSystem = new FlappyPHPantSystem( $this->container->resolveInputContext() ); // the pipes $this->pipeSystem = new PipeSystem(); // bind all systems to the scene itself $this->bindSystems([ $this->cameraSystem, $this->renderingSystem, $this->visuPhpantSystem, $this->pipeSystem, ]); }
Constructor Dont load resources or bind event listeners here, use the `load` method instead. We want to be able to load scenes without loading their resources. For example when preparing a scene to be switched or a loading screen.
__construct
php
phpgl/flappyphpant
src/Scene/GameViewScene.php
https://github.com/phpgl/flappyphpant/blob/master/src/Scene/GameViewScene.php
MIT
private function registerConsoleCommands() { $this->consoleHandlerId = $this->container->resolveVisuDispatcher()->register(DebugConsole::EVENT_CONSOLE_COMMAND, function(ConsoleCommandSignal $signal) { // do something with the console command (if you want to) var_dump($signal->commandParts); }); }
Registers the console commmand handler, for level scene specific commands
registerConsoleCommands
php
phpgl/flappyphpant
src/Scene/GameViewScene.php
https://github.com/phpgl/flappyphpant/blob/master/src/Scene/GameViewScene.php
MIT
public function attachPass(RenderPipeline $pipeline, PipelineResources $resources, RenderTargetResource $rt, float $compensation) { // we sync the profile enabled state with the debug overlay $this->container->resolveProfiler()->enabled = $this->enabled; if (!$this->enabled) { $this->rows = []; // reset the rows to avoid them stacking up self::$globalRows = []; return; } // get the actual rendering target $target = $resources->getRenderTarget($rt); // Add current FPS plus the average tick count and the compensation $this->rows[] = $this->gameLoopMetrics($compensation); $this->rows[] = "Scene: " . $this->container->resolveGame()->getCurrentScene()->getName() . ' | Press CTRL + C to open the console'; // add global rows $this->rows = array_merge($this->rows, self::$globalRows); // we render to the backbuffer $this->debugTextRenderer->attachPass($pipeline, $rt, [ new DebugOverlayText(implode("\n", $this->rows), 10, 10) ]); $profilerLines = $this->gameProfilerMetrics(); $y = $rt->height - (count($profilerLines) * $this->debugTextRenderer->lineHeight * $target->contentScaleX); $y -= 25; $this->debugTextRenderer->attachPass($pipeline, $rt, [ new DebugOverlayText(implode("\n", $profilerLines), 10, $y, new Vec3(0.726, 0.865, 1.0)), ]); // clear the rows for the next frame $this->rows = []; self::$globalRows = []; }
Draws the debug text overlay if enabled
attachPass
php
phpgl/flappyphpant
src/Debug/DebugTextOverlay.php
https://github.com/phpgl/flappyphpant/blob/master/src/Debug/DebugTextOverlay.php
MIT
public function handleWindowKey(KeySignal $signal) { // handle ESC key to close the window if ($signal->key == GLFW_KEY_ESCAPE && $signal->action == GLFW_PRESS) { $signal->window->setShouldClose(true); } }
Simple window key event handler - ESC: close the window @param KeySignal $signal
handleWindowKey
php
phpgl/flappyphpant
src/SignalHandler/WindowActionsHandler.php
https://github.com/phpgl/flappyphpant/blob/master/src/SignalHandler/WindowActionsHandler.php
MIT
public function close() { $this->closed = true; $this->client->close(); }
Close the connection to the remote endpoint
close
php
openswoole/openswoole
grpc/src/Client.php
https://github.com/openswoole/openswoole/blob/master/grpc/src/Client.php
Apache-2.0
public function send($method, $message, $type = 'proto') { $isEndStream = $this->mode === Constant::GRPC_CALL; $retry = 0; while ($retry++ < $this->settings['max_retries']) { $streamId = $this->sendMessage($method, $message, $type); if ($streamId && $streamId > 0) { $this->streams[$streamId] = [new Coroutine\Channel(1), $isEndStream]; return $streamId; } if ($this->client->errCode > 0) { throw new ClientException(Util::getErrorMessage($this->client->errCode, 9) . " {$this->client->host}:{$this->client->port}", $this->client->errCode); } Coroutine::usleep(10000); } return false; }
Send message to remote endpoint, either end the stream or not depending on $mode of the client
send
php
openswoole/openswoole
grpc/src/Client.php
https://github.com/openswoole/openswoole/blob/master/grpc/src/Client.php
Apache-2.0
public function recv($streamId, $timeout = -1) { return $this->streams[$streamId][0]->pop($timeout); }
Receive the data from a stream in the established connection based on streamId.
recv
php
openswoole/openswoole
grpc/src/Client.php
https://github.com/openswoole/openswoole/blob/master/grpc/src/Client.php
Apache-2.0
public function push($streamId, $message, $type = 'proto', $end = false) { if ($type === 'proto') { $payload = $message->serializeToString(); } elseif ($type === 'json') { $payload = $message; } $payload = pack('CN', 0, strlen($payload)) . $payload; return $this->client->write($streamId, $payload, $end); }
Push message to the remote endpoint, used in client side streaming mode. @param bool $end
push
php
openswoole/openswoole
grpc/src/Client.php
https://github.com/openswoole/openswoole/blob/master/grpc/src/Client.php
Apache-2.0
public static function getAvailableDrivers() { return [ self::DRIVER_MYSQL, ]; }
Returns the list of available drivers @return string[]
getAvailableDrivers
php
openswoole/openswoole
core/src/Coroutine/Client/PDOConfig.php
https://github.com/openswoole/openswoole/blob/master/core/src/Coroutine/Client/PDOConfig.php
Apache-2.0
function dump($var) { return highlight_string("<?php\n\$array = " . var_export($var, true) . ';', true); }
This file is part of OpenSwoole. @link https://openswoole.com @contact [email protected]
dump
php
openswoole/openswoole
example/src/Http/Server.php
https://github.com/openswoole/openswoole/blob/master/example/src/Http/Server.php
Apache-2.0
public function __clone() { $this->data = []; $this->defaults = []; $this->instances = []; }
Clone state will reset both data and instance cache.
__clone
php
spiral/framework
src/Config/src/ConfigManager.php
https://github.com/spiral/framework/blob/master/src/Config/src/ConfigManager.php
MIT
public function __construct( private readonly JsonPayloadConfig $config, ) {}
JsonPayloadMiddleware constructor.
__construct
php
spiral/framework
src/Http/src/Middleware/JsonPayloadMiddleware.php
https://github.com/spiral/framework/blob/master/src/Http/src/Middleware/JsonPayloadMiddleware.php
MIT
public function __clone() { $this->bags = []; }
Flushing bag instances when cloned.
__clone
php
spiral/framework
src/Http/src/Request/InputManager.php
https://github.com/spiral/framework/blob/master/src/Http/src/Request/InputManager.php
MIT
public function __construct(?int $code = null, string $message = '', ?\Throwable $previous = null) { if (empty($code) && empty($this->code)) { $code = self::BAD_DATA; } if (empty($message)) { $message = \sprintf('Http Error - %s', $code); } parent::__construct($message, $code, $previous); }
Code and message positions are reverted.
__construct
php
spiral/framework
src/Http/src/Exception/ClientException.php
https://github.com/spiral/framework/blob/master/src/Http/src/Exception/ClientException.php
MIT
public function __construct( private readonly string $name, private ?string $value = null, private readonly ?int $lifetime = null, private readonly ?string $path = null, private readonly ?string $domain = null, private readonly bool $secure = false, private readonly bool $httpOnly = true, ?string $sameSite = null, ) { $this->sameSite = new Cookie\SameSite($sameSite, $secure); }
New Cookie instance, cookies used to schedule cookie set while dispatching Response. @link http://php.net/manual/en/function.setcookie.php @param string $name The name of the cookie. @param string|null $value The value of the cookie. This value is stored on the clients computer; do not store sensitive information. @param int|null $lifetime Cookie lifetime. This value specified in seconds and declares period of time in which cookie will expire relatively to current time() value. @param string|null $path The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in. @param string|null $domain The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you'd set it to '.example.com'. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the spec for details. @param bool $secure Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to true, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]). @param bool $httpOnly When true the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers). @param string|null $sameSite The value of the samesite element should be either None, Lax or Strict. If any of the allowed options are not given, their default values are the same as the default values of the explicit parameters. If the samesite element is omitted, no SameSite cookie attribute is set. When Same-Site attribute is set to "None" it is required to have "Secure" attribute enable. Otherwise it will be converted to "Lax".
__construct
php
spiral/framework
src/Cookies/src/Cookie.php
https://github.com/spiral/framework/blob/master/src/Cookies/src/Cookie.php
MIT
public function __construct() { $this->r = new \ReflectionObject($this); }
AbstractDirective constructor.
__construct
php
spiral/framework
src/Stempler/src/Directive/AbstractDirective.php
https://github.com/spiral/framework/blob/master/src/Stempler/src/Directive/AbstractDirective.php
MIT
public function __construct( private string $type, private readonly string $value, ) {}
New instance of ReflectionArgument. @param string $type Argument type (see top constants). @param string $value Value in a form of php code.
__construct
php
spiral/framework
src/Tokenizer/src/Reflection/ReflectionArgument.php
https://github.com/spiral/framework/blob/master/src/Tokenizer/src/Reflection/ReflectionArgument.php
MIT
public function __construct( public readonly string|\BackedEnum|null $name = null, public readonly array $bindings = [], public readonly bool $autowire = true, ) {}
@param null|string|\BackedEnum $name Scope name. Named scopes can have individual bindings and constrains. @param array<non-empty-string, TResolver> $bindings Custom bindings for the new scope. @param bool $autowire If {@see false}, closure will be invoked with just only the passed Container as the first argument. Otherwise, {@see InvokerInterface::invoke()} will be used to invoke the closure.
__construct
php
spiral/framework
src/Core/src/Scope.php
https://github.com/spiral/framework/blob/master/src/Core/src/Scope.php
MIT
public function __construct(array $config = []) { $this->config = $config + $this->config; }
At this moment on array based configs can be supported. @param array $config Configuration data
__construct
php
spiral/framework
src/Core/src/InjectableConfig.php
https://github.com/spiral/framework/blob/master/src/Core/src/InjectableConfig.php
MIT
public function __construct( public readonly \Closure $inflector, ) { $this->parametersCount = (new \ReflectionFunction($inflector))->getNumberOfParameters(); }
@param \Closure $inflector The first closure argument is the object to be manipulated. Closure can return the new or the same object.
__construct
php
spiral/framework
src/Core/src/Config/Inflector.php
https://github.com/spiral/framework/blob/master/src/Core/src/Config/Inflector.php
MIT
public function __construct( protected readonly string $interface, public readonly bool $singleton = false, public readonly ?\Closure $fallbackFactory = null, ) { \interface_exists($interface) or throw new \InvalidArgumentException( "Interface `{$interface}` does not exist.", ); $this->singleton and $this->fallbackFactory !== null and throw new \InvalidArgumentException( 'Singleton proxies must not have a fallback factory.', ); }
@template T @param class-string<T> $interface @param null|\Closure(ContainerInterface, \Stringable|string|null): T $fallbackFactory Factory that will be used to create an instance if the value is resolved from a proxy.
__construct
php
spiral/framework
src/Core/src/Config/Proxy.php
https://github.com/spiral/framework/blob/master/src/Core/src/Config/Proxy.php
MIT
public function __construct(string $class) { $this->reflection = new \ReflectionClass($class); }
Only support SchematicEntity classes!
__construct
php
spiral/framework
src/Models/src/Reflection/ReflectionEntity.php
https://github.com/spiral/framework/blob/master/src/Models/src/Reflection/ReflectionEntity.php
MIT
public static function getResource(StreamInterface $stream) { $mode = null; if ($stream->isReadable()) { $mode = 'r'; } if ($stream->isWritable()) { $mode = !empty($mode) ? 'r+' : 'w'; } if (empty($mode)) { throw new WrapperException('Stream is not available in read or write modes'); } $result = \fopen(self::getFilename($stream), $mode); return $result === false ? throw new WrapperException(\sprintf('Unable to open stream `%s`.', $stream->getMetadata('uri'))) : $result; }
Create StreamInterface associated resource. @return resource @throws WrapperException
getResource
php
spiral/framework
src/Streams/src/StreamWrapper.php
https://github.com/spiral/framework/blob/master/src/Streams/src/StreamWrapper.php
MIT
function env(string $key, mixed $default = null) { return spiral(EnvironmentInterface::class)->get($key, $default); }
Gets the value of an environment variable. Uses application core from the current global scope. @param non-empty-string $key @return mixed
env
php
spiral/framework
src/Boot/src/helpers.php
https://github.com/spiral/framework/blob/master/src/Boot/src/helpers.php
MIT
public function __construct() { $this->dates = new DateTimeFactory(); $this->intervals = new DateTimeIntervalFactory($this->dates); $this->expiration = $this->intervals->create(static::DEFAULT_EXPIRATION_INTERVAL); }
ExpirationAwareResolver constructor.
__construct
php
spiral/framework
src/Distribution/src/Resolver/ExpirationAwareResolver.php
https://github.com/spiral/framework/blob/master/src/Distribution/src/Resolver/ExpirationAwareResolver.php
MIT
public function make(ResourceInterface $resource, SerializerAbstract $serializer, array $options = []) { $options = $this->parseOptions($options, $resource); return $this->manager->setSerializer($serializer) ->parseIncludes($options['includes']) ->parseExcludes($options['excludes']) ->parseFieldsets($options['fieldsets']) ->createData($resource) ->toArray(); }
Transform the given resource, and serialize the data with the given serializer. @param \League\Fractal\Resource\ResourceInterface $resource @param \League\Fractal\Serializer\SerializerAbstract $serializer @param array $options @return array|null
make
php
flugg/laravel-responder
src/FractalTransformFactory.php
https://github.com/flugg/laravel-responder/blob/master/src/FractalTransformFactory.php
MIT
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
registerTransformerBindings
php
flugg/laravel-responder
src/ResponderServiceProvider.php
https://github.com/flugg/laravel-responder/blob/master/src/ResponderServiceProvider.php
MIT
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
registerTransformationBindings
php
flugg/laravel-responder
src/ResponderServiceProvider.php
https://github.com/flugg/laravel-responder/blob/master/src/ResponderServiceProvider.php
MIT
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
bootLaravelApplication
php
flugg/laravel-responder
src/ResponderServiceProvider.php
https://github.com/flugg/laravel-responder/blob/master/src/ResponderServiceProvider.php
MIT
protected function bootLumenApplication() { $this->app->configure('responder'); }
Bootstrap the Lumen application. @return void
bootLumenApplication
php
flugg/laravel-responder
src/ResponderServiceProvider.php
https://github.com/flugg/laravel-responder/blob/master/src/ResponderServiceProvider.php
MIT
public function register($errorCode, string $message) { $this->messages = array_merge($this->messages, is_array($errorCode) ? $errorCode : [ $errorCode => $message, ]); }
Register a message mapped to an error code. @param mixed $errorCode @param string $message @return void
register
php
flugg/laravel-responder
src/ErrorMessageResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/ErrorMessageResolver.php
MIT
public function resolve($errorCode) { if (key_exists($errorCode, $this->messages)) { return $this->messages[$errorCode]; } if ($this->translator->has($errorCode = "errors.$errorCode")) { return $this->translator->get($errorCode); } return null; }
Resolve a message from the given error code. @param mixed $errorCode @return string|null
resolve
php
flugg/laravel-responder
src/ErrorMessageResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/ErrorMessageResolver.php
MIT
public function cursor(Cursor $cursor) { if ($this->resource instanceof CollectionResource) { $this->resource->setCursor($cursor); } return $this; }
Manually set the cursor on the resource. @param \League\Fractal\Pagination\Cursor $cursor @return $this
cursor
php
flugg/laravel-responder
src/TransformBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/TransformBuilder.php
MIT
public function paginator(IlluminatePaginatorAdapter $paginator) { if ($this->resource instanceof CollectionResource) { $this->resource->setPaginator($paginator); } return $this; }
Manually set the paginator on the resource. @param \League\Fractal\Pagination\IlluminatePaginatorAdapter $paginator @return $this
paginator
php
flugg/laravel-responder
src/TransformBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/TransformBuilder.php
MIT
public function meta(array $data) { $this->resource->setMeta($data); return $this; }
Add meta data appended to the response data. @param array $data @return $this
meta
php
flugg/laravel-responder
src/TransformBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/TransformBuilder.php
MIT
public function without($relations) { $this->without = array_merge($this->without, is_array($relations) ? $relations : func_get_args()); return $this; }
Exclude relations from the transform. @param string[]|string $relations @return $this
without
php
flugg/laravel-responder
src/TransformBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/TransformBuilder.php
MIT
public function only($fields) { $this->only = array_merge($this->only, is_array($fields) ? $fields : func_get_args()); return $this; }
Filter fields to output using sparse fieldsets. @param string[]|string $fields @return $this
only
php
flugg/laravel-responder
src/TransformBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/TransformBuilder.php
MIT
public function transform() { $this->prepareRelations($this->resource->getData(), $this->resource->getTransformer()); return $this->transformFactory->make($this->resource ?: new NullResource, $this->serializer, [ 'includes' => $this->with, 'excludes' => $this->without, 'fieldsets' => $this->only, ]); }
Transform and serialize the data and return the transformed array. @return array|null
transform
php
flugg/laravel-responder
src/TransformBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/TransformBuilder.php
MIT
protected function prepareRelations($data, $transformer) { if ($transformer instanceof Transformer) { $relations = $transformer->relations($this->with); $defaultRelations = $this->removeExcludedRelations($transformer->defaultRelations($this->with)); $this->with = array_merge($relations, $defaultRelations); } if ($data instanceof Model || $data instanceof Collection) { $this->eagerLoadRelations($data, $this->with, $transformer); } $this->with = array_keys($this->with); }
Prepare requested relations for the transformation. @param mixed $data @param \Flugg\Responder\Transformers\Transformer|callable|string|null $transformer @return void
prepareRelations
php
flugg/laravel-responder
src/TransformBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/TransformBuilder.php
MIT
protected function setStatusCode(int $status) { $this->validateStatusCode($this->status = $status); }
Set the HTTP status code for the response. @param int $status @return void
setStatusCode
php
flugg/laravel-responder
src/Http/Responses/ResponseBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/Http/Responses/ResponseBuilder.php
MIT
public function error($errorCode = null, ?string $message = null) { $this->errorCode = $errorCode; $this->message = $message; return $this; }
Set the error code and message. @param mixed|null $errorCode @param string|null $message @return $this
error
php
flugg/laravel-responder
src/Http/Responses/ErrorResponseBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/Http/Responses/ErrorResponseBuilder.php
MIT
public function data(?array $data = null) { $this->data = array_merge((array) $this->data, (array) $data); return $this; }
Add additional data to the error. @param array|null $data @return $this
data
php
flugg/laravel-responder
src/Http/Responses/ErrorResponseBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/Http/Responses/ErrorResponseBuilder.php
MIT
protected function validateStatusCode(int $status) { if ($status < 400 || $status >= 600) { throw new InvalidArgumentException("{$status} is not a valid error HTTP status code."); } }
Validate the HTTP status code for the response. @param int $status @return void @throws \InvalidArgumentException
validateStatusCode
php
flugg/laravel-responder
src/Http/Responses/ErrorResponseBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/Http/Responses/ErrorResponseBuilder.php
MIT
public function __call($name, $arguments) { if (in_array($name, ['cursor', 'paginator', 'meta', 'with', 'without', 'only', 'serializer'])) { $this->transformBuilder->$name(...$arguments); return $this; } throw new BadMethodCallException; }
Dynamically send calls to the transform builder. @param string $name @param array $arguments @return self|void
__call
php
flugg/laravel-responder
src/Http/Responses/SuccessResponseBuilder.php
https://github.com/flugg/laravel-responder/blob/master/src/Http/Responses/SuccessResponseBuilder.php
MIT
public function __construct(ResponseFactory $factory) { $this->factory = $factory; }
Construct the decorator class. @param \Flugg\Responder\Contracts\ResponseFactory $factory
__construct
php
flugg/laravel-responder
src/Http/Responses/Decorators/ResponseDecorator.php
https://github.com/flugg/laravel-responder/blob/master/src/Http/Responses/Decorators/ResponseDecorator.php
MIT
protected function seeSuccess($data = null, $status = 200) { $response = $this->seeSuccessResponse($data, $status); $this->seeSuccessData($response->getData(true)['data']); return $this; }
Assert that the response is a valid success response. @param mixed $data @param int $status @return $this
seeSuccess
php
flugg/laravel-responder
src/Testing/MakesApiRequests.php
https://github.com/flugg/laravel-responder/blob/master/src/Testing/MakesApiRequests.php
MIT
protected function seeSuccessStructure($data = null) { $this->seeJsonStructure([ 'data' => $data, ]); return $this; }
Assert that the response data contains the given structure. @param mixed $data @return $this
seeSuccessStructure
php
flugg/laravel-responder
src/Testing/MakesApiRequests.php
https://github.com/flugg/laravel-responder/blob/master/src/Testing/MakesApiRequests.php
MIT
protected function seeSuccessData($data = null) { collect($data)->each(function ($value, $key) { if (is_array($value)) { $this->seeSuccessData($value); } else { $this->seeJson([$key => $value]); } }); return $this; }
Assert that the response data contains given values. @param mixed $data @return $this
seeSuccessData
php
flugg/laravel-responder
src/Testing/MakesApiRequests.php
https://github.com/flugg/laravel-responder/blob/master/src/Testing/MakesApiRequests.php
MIT
protected function seeError(string $error, ?int $status = null) { if (! is_null($status)) { $this->seeStatusCode($status); } if ($this->app->config->get('responder.status_code')) { $this->seeJson([ 'status' => $status, ]); } return $this->seeJson([ 'success' => false, ])->seeJsonSubset([ 'error' => [ 'code' => $error, ], ]); }
Assert that the response is a valid error response. @param string $error @param int|null $status @return $this
seeError
php
flugg/laravel-responder
src/Testing/MakesApiRequests.php
https://github.com/flugg/laravel-responder/blob/master/src/Testing/MakesApiRequests.php
MIT
public function __construct($data, $cursor, $previousCursor, $nextCursor) { $this->cursor = $cursor; $this->previousCursor = $previousCursor; $this->nextCursor = $nextCursor; $this->set($data); }
Create a new paginator instance. @param \Illuminate\Support\Collection|array|null $data @param int|string|null $cursor @param int|string|null $previousCursor @param int|string|null $nextCursor
__construct
php
flugg/laravel-responder
src/Pagination/CursorPaginator.php
https://github.com/flugg/laravel-responder/blob/master/src/Pagination/CursorPaginator.php
MIT
public function previous() { return $this->previousCursor; }
Retireve the next cursor reference. @return int|string|null
previous
php
flugg/laravel-responder
src/Pagination/CursorPaginator.php
https://github.com/flugg/laravel-responder/blob/master/src/Pagination/CursorPaginator.php
MIT
public static function resolveCursor(string $name = 'cursor') { if (isset(static::$currentCursorResolver)) { return call_user_func(static::$currentCursorResolver, $name); } throw new LogicException("Could not resolve cursor with the name [{$name}]."); }
Resolve the current cursor using the cursor resolver. @param string $name @return mixed @throws \LogicException
resolveCursor
php
flugg/laravel-responder
src/Pagination/CursorPaginator.php
https://github.com/flugg/laravel-responder/blob/master/src/Pagination/CursorPaginator.php
MIT
public static function cursorResolver(Closure $resolver) { static::$currentCursorResolver = $resolver; }
Set the current cursor resolver callback. @param \Closure $resolver @return void
cursorResolver
php
flugg/laravel-responder
src/Pagination/CursorPaginator.php
https://github.com/flugg/laravel-responder/blob/master/src/Pagination/CursorPaginator.php
MIT
public function __construct() { parent::__construct('Serializer must be an instance of [' . ErrorSerializer::class . '].'); }
Construct the exception class.
__construct
php
flugg/laravel-responder
src/Exceptions/InvalidErrorSerializerException.php
https://github.com/flugg/laravel-responder/blob/master/src/Exceptions/InvalidErrorSerializerException.php
MIT
protected function convert($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|\Throwable $exception @param array $convert @return void
convert
php
flugg/laravel-responder
src/Exceptions/ConvertsExceptions.php
https://github.com/flugg/laravel-responder/blob/master/src/Exceptions/ConvertsExceptions.php
MIT
public function render($request, $exception) { if ($request->wantsJson()) { $this->convertDefaultException($exception); if ($exception instanceof HttpException) { return $this->renderResponse($exception); } } return parent::render($request, $exception); }
Render an exception into an HTTP response. @param \Illuminate\Http\Request $request @param \Exception|\Throwable $exception @return \Symfony\Component\HttpFoundation\Response
render
php
flugg/laravel-responder
src/Exceptions/Handler.php
https://github.com/flugg/laravel-responder/blob/master/src/Exceptions/Handler.php
MIT
public function __construct(?string $message = null, ?array $headers = null) { parent::__construct($this->status, $message ?? $this->message, null, $headers ?? $this->headers); }
Construct the exception class. @param string|null $message @param array|null $headers
__construct
php
flugg/laravel-responder
src/Exceptions/Http/HttpException.php
https://github.com/flugg/laravel-responder/blob/master/src/Exceptions/Http/HttpException.php
MIT
public function data() { return $this->data; }
Retrieve additional error data. @return array|null
data
php
flugg/laravel-responder
src/Exceptions/Http/HttpException.php
https://github.com/flugg/laravel-responder/blob/master/src/Exceptions/Http/HttpException.php
MIT
public function __construct(Validator $validator) { $this->validator = $validator; parent::__construct(); }
Construct the exception class. @param \Illuminate\Contracts\Validation\Validator $validator
__construct
php
flugg/laravel-responder
src/Exceptions/Http/ValidationFailedException.php
https://github.com/flugg/laravel-responder/blob/master/src/Exceptions/Http/ValidationFailedException.php
MIT
protected function getDefaultNamespace($rootNamespace) { return $rootNamespace . '\Transformers'; }
Get the default namespace for the class. @param string $rootNamespace @return string
getDefaultNamespace
php
flugg/laravel-responder
src/Console/MakeTransformer.php
https://github.com/flugg/laravel-responder/blob/master/src/Console/MakeTransformer.php
MIT
protected function resolveModelFromClassName() { return 'App\\Models\\' . str_replace('Transformer', '', Arr::last(explode('/', $this->getNameInput()))); }
Resolve a model from the given class name. @return string
resolveModelFromClassName
php
flugg/laravel-responder
src/Console/MakeTransformer.php
https://github.com/flugg/laravel-responder/blob/master/src/Console/MakeTransformer.php
MIT
protected function buildModelReplacements(array $replace) { if (! class_exists($modelClass = $this->parseModel($this->option('model')))) { if ($this->confirm("A {$modelClass} model does not exist. Do you want to generate it?", true)) { $this->call('make:model', ['name' => $modelClass]); } } return array_merge($replace, [ 'DummyFullModelClass' => $modelClass, 'DummyModelClass' => class_basename($modelClass), 'DummyModelVariable' => lcfirst(class_basename($modelClass)), ]); }
Build the model replacement values. @param array $replace @return array
buildModelReplacements
php
flugg/laravel-responder
src/Console/MakeTransformer.php
https://github.com/flugg/laravel-responder/blob/master/src/Console/MakeTransformer.php
MIT
protected function parseModel($model) { if (preg_match('([^A-Za-z0-9_/\\\\])', $model)) { throw new InvalidArgumentException('Model name contains invalid characters.'); } $model = trim(str_replace('/', '\\', $model), '\\'); if (! Str::startsWith($model, $rootNamespace = $this->laravel->getNamespace())) { $model = $rootNamespace . $model; } return $model; }
Get the fully-qualified model class name. @param string $model @return string
parseModel
php
flugg/laravel-responder
src/Console/MakeTransformer.php
https://github.com/flugg/laravel-responder/blob/master/src/Console/MakeTransformer.php
MIT
public static function containerResolver(Closure $resolver) { static::$containerResolver = $resolver; }
Set a container using a resolver callback. @param \Closure $resolver @return void
containerResolver
php
flugg/laravel-responder
src/Transformers/Transformer.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/Transformer.php
MIT
protected function resolveTransformer(string $transformer) { $transformerResolver = $this->resolveContainer()->make(TransformerResolver::class); return $transformerResolver->resolve($transformer); }
Resolve a transformer from a class name string. @param string $transformer @return mixed
resolveTransformer
php
flugg/laravel-responder
src/Transformers/Transformer.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/Transformer.php
MIT
public function bind($transformable, $transformer = null) { $this->bindings = array_merge($this->bindings, is_array($transformable) ? $transformable : [ $transformable => $transformer, ]); }
Register a transformable to transformer binding. @param string|array $transformable @param string|callback|null $transformer @return void
bind
php
flugg/laravel-responder
src/Transformers/TransformerResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/TransformerResolver.php
MIT
public function resolveFromData($data) { $transformer = $this->resolveTransformer($this->resolveTransformableItem($data)); return $this->resolve($transformer); }
Resolve a transformer from the given data. @param mixed $data @return \Flugg\Responder\Transformers\Transformer|callable
resolveFromData
php
flugg/laravel-responder
src/Transformers/TransformerResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/TransformerResolver.php
MIT
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
resolveTransformer
php
flugg/laravel-responder
src/Transformers/TransformerResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/TransformerResolver.php
MIT
protected function resolveTransformableItem($data) { if (is_array($data) || $data instanceof Traversable) { foreach ($data as $item) { return $item; } } return $data; }
Resolve a transformable item from the given data. @param mixed $data @return mixed
resolveTransformableItem
php
flugg/laravel-responder
src/Transformers/TransformerResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/TransformerResolver.php
MIT
protected function resolveRelation(Model $model, string $identifier) { if(config('responder.use_camel_case_relations')) { $identifier = Str::camel($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
resolveRelation
php
flugg/laravel-responder
src/Transformers/Concerns/HasRelationships.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/Concerns/HasRelationships.php
MIT
protected function mappedTransformerClass(string $identifier) { return $this->availableRelations()[$identifier] ?? null; }
Get a related transformer class mapped to a relation identifier. @param string $identifier @return string|null
mappedTransformerClass
php
flugg/laravel-responder
src/Transformers/Concerns/HasRelationships.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/Concerns/HasRelationships.php
MIT
protected function callIncludeMethod(Scope $scope, $identifier, $data) { $parameters = iterator_to_array($scope->getManager()->getIncludeParams($scope->getIdentifier($identifier))); return $this->includeResource($identifier, $data, $parameters); }
Overrides Fractal's method for including a relation. @param \League\Fractal\Scope $scope @param string $identifier @param mixed $data @return \League\Fractal\Resource\ResourceInterface
callIncludeMethod
php
flugg/laravel-responder
src/Transformers/Concerns/OverridesFractal.php
https://github.com/flugg/laravel-responder/blob/master/src/Transformers/Concerns/OverridesFractal.php
MIT
public function bind($transformable, string $resourceKey) { $this->bindings = array_merge($this->bindings, is_array($transformable) ? $transformable : [ $transformable => $resourceKey, ]); }
Register a transformable to resource key binding. @param string|array $transformable @param string $resourceKey @return void
bind
php
flugg/laravel-responder
src/Resources/ResourceKeyResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/Resources/ResourceKeyResolver.php
MIT
public function resolve($data) { $transformable = $this->resolveTransformableItem($data); if (is_object($transformable) && key_exists(get_class($transformable), $this->bindings)) { return $this->bindings[get_class($transformable)]; } if ($transformable instanceof Model) { return $this->resolveFromModel($transformable); } return 'data'; }
Resolve a resource key from the given data. @param mixed $data @return string
resolve
php
flugg/laravel-responder
src/Resources/ResourceKeyResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/Resources/ResourceKeyResolver.php
MIT
public function resolveFromModel(Model $model) { if (method_exists($model, 'getResourceKey')) { return $model->getResourceKey(); } return $model->getTable(); }
Resolve a resource key from the given model. @param \Illuminate\Database\Eloquent\Model $model @return string
resolveFromModel
php
flugg/laravel-responder
src/Resources/ResourceKeyResolver.php
https://github.com/flugg/laravel-responder/blob/master/src/Resources/ResourceKeyResolver.php
MIT
protected function getPackageProviders($app) { return [ ResponderServiceProvider::class, ]; }
Get package service providers. @param \Illuminate\Foundation\Application $app @return array
getPackageProviders
php
flugg/laravel-responder
tests/TestCase.php
https://github.com/flugg/laravel-responder/blob/master/tests/TestCase.php
MIT
public function __construct(AbstractBrowser $client, ?string $baseUrl = null) { $this->client = $client; $this->client->followRedirects(true); if ($baseUrl !== null && $client instanceof HttpKernelBrowser) { $basePath = parse_url($baseUrl, PHP_URL_PATH); if (\is_string($basePath)) { $client->setServerParameter('SCRIPT_FILENAME', $basePath); } } }
Initializes BrowserKit driver. @param AbstractBrowser<TRequest, TResponse> $client @param string|null $baseUrl Base URL for HttpKernel clients
__construct
php
minkphp/MinkBrowserKitDriver
src/BrowserKitDriver.php
https://github.com/minkphp/MinkBrowserKitDriver/blob/master/src/BrowserKitDriver.php
MIT
protected function prepareUrl(string $url) { return $url; }
Prepares URL for visiting. Removes "*.php/" from urls and then passes it to BrowserKitDriver::visit(). @param string $url @return string
prepareUrl
php
minkphp/MinkBrowserKitDriver
src/BrowserKitDriver.php
https://github.com/minkphp/MinkBrowserKitDriver/blob/master/src/BrowserKitDriver.php
MIT
protected function getFormField(string $xpath) { $fieldNode = $this->getCrawlerNode($this->getFilteredCrawler($xpath)); $fieldType = $fieldNode->getAttribute('type'); if (\in_array($fieldType, ['button', 'submit', 'image'], true)) { throw new DriverException(sprintf('Cannot access a form field of type "%s".', $fieldType)); } $fieldName = str_replace('[]', '', $fieldNode->getAttribute('name')); $formNode = $this->getFormNode($fieldNode); $formId = $this->getFormNodeId($formNode); if (!isset($this->forms[$formId])) { $this->forms[$formId] = new Form($formNode, $this->getCurrentUrl()); } if (is_array($this->forms[$formId][$fieldName])) { $positionField = $this->forms[$formId][$fieldName][$this->getFieldPosition($fieldNode)]; \assert($positionField instanceof FormField); return $positionField; } return $this->forms[$formId][$fieldName]; }
Returns form field from XPath query. @param string $xpath @return FormField @throws DriverException @throws \InvalidArgumentException when the field does not exist in the BrowserKit form
getFormField
php
minkphp/MinkBrowserKitDriver
src/BrowserKitDriver.php
https://github.com/minkphp/MinkBrowserKitDriver/blob/master/src/BrowserKitDriver.php
MIT
public function __construct(string $message = '', int $code = 0, ?Throwable $previous = null) { parent::__construct($message, $code, $previous); }
DEPRECATION WARNING! This class will be removed in the next major point release. @deprecated since version 9.7.0
__construct
php
thephpleague/csv
src/SyntaxError.php
https://github.com/thephpleague/csv/blob/master/src/SyntaxError.php
MIT
public function getSocket() { return $this->socket; }
Return socket resource if is exist @return resource
getSocket
php
EvilFreelancer/routeros-api-php
src/SocketTrait.php
https://github.com/EvilFreelancer/routeros-api-php/blob/master/src/SocketTrait.php
MIT
public function key() { return $this->current; }
Return the key of the current element @return mixed
key
php
EvilFreelancer/routeros-api-php
src/ResponseIterator.php
https://github.com/EvilFreelancer/routeros-api-php/blob/master/src/ResponseIterator.php
MIT
private function config(string $parameter) { return $this->config->get($parameter); }
Get some parameter from config @param string $parameter Name of required parameter @return mixed @throws \RouterOS\Exceptions\ConfigException
config
php
EvilFreelancer/routeros-api-php
src/Client.php
https://github.com/EvilFreelancer/routeros-api-php/blob/master/src/Client.php
MIT
public function readRAW(array $options = []) { // By default response is empty $response = []; // We have to wait a !done or !fatal $lastReply = false; // Count !re in response $countResponse = 0; // Convert strings to array and return results if ($this->isCustomOutput()) { // Return RAW configuration return $this->customOutput; } // Read answer from socket in loop, or until timeout reached $startTime = time(); while (true) { // Exit from loop if timeout reached if (time() > $startTime + $this->config('socket_timeout')) { throw new ClientException('Socket timeout reached'); } $word = $this->connector->readWord(); //Limit response number to finish the read if (isset($options['count']) && $countResponse >= (int) $options['count']) { $lastReply = true; } if ('' === $word) { if ($lastReply) { // We received a !done or !fatal message in a precedent loop // response is complete break; } // We did not receive the !done or !fatal message // This 0 length message is the end of a reply !re or !trap // We have to wait the router to send a !done or !fatal reply followed by optionals values and a 0 length message continue; } // Save output line to response array $response[] = $word; // If we get a !done or !fatal line in response, we are now ready to finish the read // but we need to wait a 0 length message, switch the flag if ('!done' === $word || '!fatal' === $word) { $lastReply = true; } // If we get a !re line in response, we increment the variable if ('!re' === $word) { $countResponse++; } } // Parse results and return return $response; }
Read RAW response from RouterOS, it can be /export command results also, not only array from API @param array $options Additional options @return array|string @since 1.0.0
readRAW
php
EvilFreelancer/routeros-api-php
src/Client.php
https://github.com/EvilFreelancer/routeros-api-php/blob/master/src/Client.php
MIT
public function read(bool $parse = true, array $options = []) { // Read RAW response $response = $this->readRAW($options); // Return RAW configuration if custom output is set if ($this->isCustomOutput()) { $this->customOutput = null; return $response; } // Parse results and return return $parse ? $this->rosario($response) : $response; }
Read answer from server after query was executed A Mikrotik reply is formed of blocks Each block starts with a word, one of ('!re', '!trap', '!done', '!fatal') Each block end with an zero byte (empty line) Reply ends with a complete !done or !fatal block (ended with 'empty line') A !fatal block precedes TCP connexion close @param bool $parse If need parse output to array @param array $options Additional options @return mixed
read
php
EvilFreelancer/routeros-api-php
src/Client.php
https://github.com/EvilFreelancer/routeros-api-php/blob/master/src/Client.php
MIT
public static function checkIfKeysNotExist(array $keys, array $array) { $output = []; foreach ($keys as $key) { if (self::checkIfKeyNotExist($key, $array)) { $output[] = $key; } } return !empty($output) ? implode(',', $output) : true; }
Check if required keys in array of parameters @param array $keys @param array $array @return array|bool Return true if all fine, and string with name of key which was not found
checkIfKeysNotExist
php
EvilFreelancer/routeros-api-php
src/Helpers/ArrayHelper.php
https://github.com/EvilFreelancer/routeros-api-php/blob/master/src/Helpers/ArrayHelper.php
MIT
public function decimals($decimals) { $this->decimals = $decimals; return $this; }
Set the invoice decimal precision. @method decimals @param int $decimals @return self
decimals
php
ConsoleTVs/Invoices
Traits/Setters.php
https://github.com/ConsoleTVs/Invoices/blob/master/Traits/Setters.php
MIT