code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
private function willQueryRelated($record, $relationshipName, $parameters, $expected) { $mock = $this->relationshipAdapter(); $mock->expects($this->atLeastOnce()) ->method('query') ->with($record, $parameters) ->willReturn($expected); return $this->adapter([$relationshipName => $mock]); }
@param $record @param $relationshipName @param $parameters @param $expected @return MockObject
willQueryRelated
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Store/StoreTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Store/StoreTest.php
Apache-2.0
private function willQueryRelationship($record, $relationshipName, $parameters, $expected) { $mock = $this->relationshipAdapter(); $mock->expects($this->atLeastOnce()) ->method('relationship') ->with($record, $parameters) ->willReturn($expected); return $this->adapter([$relationshipName => $mock]); }
@param $record @param $relationshipName @param $parameters @param $expected @return MockObject
willQueryRelationship
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Store/StoreTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Store/StoreTest.php
Apache-2.0
public function testNull($method) { $actual = call_user_func(Arr::class . "::{$method}", null); $this->assertSame([], $actual); }
Test that the conversion methods accept null as a value. @param $method @dataProvider methodsProvider
testNull
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Utils/ArrTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Utils/ArrTest.php
Apache-2.0
public function testDasherize($value, $expected) { $this->assertSame($expected, Str::dasherize($value)); }
@param $value @param $expected @dataProvider dasherizeProvider
testDasherize
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Utils/StrTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Utils/StrTest.php
Apache-2.0
public function testDecamelize($value, $expected) { $this->assertSame($expected, Str::decamelize($value)); }
@param $value @param $expected @dataProvider decamelizeProvider
testDecamelize
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Utils/StrTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Utils/StrTest.php
Apache-2.0
public function testUnderscore($value, $expected) { $this->assertSame($expected, Str::underscore($value)); }
@param $value @param $expected @dataProvider underscoreProvider
testUnderscore
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Utils/StrTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Utils/StrTest.php
Apache-2.0
public function testCamelizeAndClassify($value, $expected) { $this->assertSame($expected, Str::camelize($value), 'camelize'); $this->assertSame(ucfirst($expected), Str::classify($value), 'classify'); }
@param $value @param $expected @dataProvider camelizeProvider
testCamelizeAndClassify
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Utils/StrTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Utils/StrTest.php
Apache-2.0
public function test(array $fields, bool $expected) { $rule = new AllowedFieldSets([ 'posts' => ['title', 'content', 'author'], 'users' => 'name', 'tags' => null, // any allowed 'countries' => [], // none allowed ]); $this->assertSame($expected, $rule->passes('fields', $fields)); }
@param array $fields @param bool $expected @dataProvider allowedProvider
test
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Validation/Rules/AllowedFieldSetsTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Validation/Rules/AllowedFieldSetsTest.php
Apache-2.0
public function testWithMethods(array $fields, bool $expected) { $rule = (new AllowedFieldSets()) ->allow('posts', ['title', 'content', 'author']) ->allow('users', ['name']) ->any('tags') ->none('countries'); $this->assertSame($expected, $rule->passes('fields', $fields)); }
@param array $fields @param bool $expected @dataProvider allowedProvider
testWithMethods
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Validation/Rules/AllowedFieldSetsTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Validation/Rules/AllowedFieldSetsTest.php
Apache-2.0
public function testValid($types, $value): void { $types = (array) $types; $rule = new HasMany(...$types); $this->assertTrue($rule->passes('authors', $value)); }
@param $types @param $value @dataProvider validProvider
testValid
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Validation/Rules/HasManyTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Validation/Rules/HasManyTest.php
Apache-2.0
public function testInvalid($types, $value): void { $types = (array) $types; $rule = new HasMany(...$types); $this->assertFalse($rule->passes('authors', $value)); }
@param $types @param $value @dataProvider invalidProvider
testInvalid
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Validation/Rules/HasManyTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Validation/Rules/HasManyTest.php
Apache-2.0
public function testValid($types, $value): void { $types = (array) $types; $rule = new HasOne(...$types); $this->assertTrue($rule->passes('author', $value)); }
@param $types @param $value @dataProvider validProvider
testValid
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Validation/Rules/HasOneTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Validation/Rules/HasOneTest.php
Apache-2.0
public function testInvalid($types, $value): void { $types = (array) $types; $rule = new HasOne(...$types); $this->assertFalse($rule->passes('author', $value)); }
@param $types @param $value @dataProvider invalidProvider
testInvalid
php
cloudcreativity/laravel-json-api
tests/lib/Unit/Validation/Rules/HasOneTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/Validation/Rules/HasOneTest.php
Apache-2.0
private function withEncoder($name = null, $options = 0, $depth = 512, ?QueryParameters $parameters = null) { $post = (object) ['type' => 'posts', 'id' => '1']; $encoder = $this->createMock(Encoder::class); $encoder->expects($this->once())->method('withEncodingParameters')->with($parameters)->willReturnSelf(); $encoder->expects($this->once())->method('encodeData')->with($post); $this->api->expects($this->once())->method('encoder')->with($options, $depth)->willReturn($encoder); $this->service->method('api')->with($name)->willReturn($this->api); return $post; }
@param $name @param int $options @param int $depth @param QueryParameters|null $parameters @return object
withEncoder
php
cloudcreativity/laravel-json-api
tests/lib/Unit/View/RendererTest.php
https://github.com/cloudcreativity/laravel-json-api/blob/master/tests/lib/Unit/View/RendererTest.php
Apache-2.0
public function getMethodSynopsisDocument(array $funcMap, array $aliasMap): ?string { $doc = new DOMDocument(); $doc->formatOutput = true; $methodSynopsis = $this->getMethodSynopsisElement($funcMap, $aliasMap, $doc); if (!$methodSynopsis) { return null; } $doc->appendChild($methodSynopsis); return $doc->saveXML(); }
@param FuncInfo[] $funcMap @param FuncInfo[] $aliasMap @throws Exception
getMethodSynopsisDocument
php
awslabs/aws-crt-php
gen_stub.php
https://github.com/awslabs/aws-crt-php/blob/master/gen_stub.php
Apache-2.0
public function getMethodSynopsisElement(array $funcMap, array $aliasMap, DOMDocument $doc): ?DOMElement { if ($this->hasParamWithUnknownDefaultValue()) { return null; } if ($this->name->isConstructor()) { $synopsisType = "constructorsynopsis"; } elseif ($this->name->isDestructor()) { $synopsisType = "destructorsynopsis"; } else { $synopsisType = "methodsynopsis"; } $methodSynopsis = $doc->createElement($synopsisType); $aliasedFunc = $this->aliasType === "alias" && isset($funcMap[$this->alias->__toString()]) ? $funcMap[$this->alias->__toString()] : null; $aliasFunc = $aliasMap[$this->name->__toString()] ?? null; if (($this->aliasType === "alias" && $aliasedFunc !== null && $aliasedFunc->isMethod() !== $this->isMethod()) || ($aliasFunc !== null && $aliasFunc->isMethod() !== $this->isMethod()) ) { $role = $doc->createAttribute("role"); $role->value = $this->isMethod() ? "oop" : "procedural"; $methodSynopsis->appendChild($role); } $methodSynopsis->appendChild(new DOMText("\n ")); foreach ($this->getModifierNames() as $modifierString) { $modifierElement = $doc->createElement('modifier', $modifierString); $methodSynopsis->appendChild($modifierElement); $methodSynopsis->appendChild(new DOMText(" ")); } $returnType = $this->return->getMethodSynopsisType(); if ($returnType) { $this->appendMethodSynopsisTypeToElement($doc, $methodSynopsis, $returnType); } $methodname = $doc->createElement('methodname', $this->name->__toString()); $methodSynopsis->appendChild($methodname); if (empty($this->args)) { $methodSynopsis->appendChild(new DOMText("\n ")); $void = $doc->createElement('void'); $methodSynopsis->appendChild($void); } else { foreach ($this->args as $arg) { $methodSynopsis->appendChild(new DOMText("\n ")); $methodparam = $doc->createElement('methodparam'); if ($arg->defaultValue !== null) { $methodparam->setAttribute("choice", "opt"); } if ($arg->isVariadic) { $methodparam->setAttribute("rep", "repeat"); } $methodSynopsis->appendChild($methodparam); $this->appendMethodSynopsisTypeToElement($doc, $methodparam, $arg->getMethodSynopsisType()); $parameter = $doc->createElement('parameter', $arg->name); if ($arg->sendBy !== ArgInfo::SEND_BY_VAL) { $parameter->setAttribute("role", "reference"); } $methodparam->appendChild($parameter); $defaultValue = $arg->getDefaultValueAsMethodSynopsisString(); if ($defaultValue !== null) { $initializer = $doc->createElement('initializer'); if (preg_match('/^[a-zA-Z_][a-zA-Z_0-9]*$/', $defaultValue)) { $constant = $doc->createElement('constant', $defaultValue); $initializer->appendChild($constant); } else { $initializer->nodeValue = $defaultValue; } $methodparam->appendChild($initializer); } } } $methodSynopsis->appendChild(new DOMText("\n ")); return $methodSynopsis; }
@param FuncInfo[] $funcMap @param FuncInfo[] $aliasMap @throws Exception
getMethodSynopsisElement
php
awslabs/aws-crt-php
gen_stub.php
https://github.com/awslabs/aws-crt-php/blob/master/gen_stub.php
Apache-2.0
function generateMethodSynopses(array $funcMap, array $aliasMap): array { $result = []; foreach ($funcMap as $funcInfo) { $methodSynopsis = $funcInfo->getMethodSynopsisDocument($funcMap, $aliasMap); if ($methodSynopsis !== null) { $result[$funcInfo->name->getMethodSynopsisFilename() . ".xml"] = $methodSynopsis; } } return $result; }
@param FuncInfo[] $funcMap @param FuncInfo[] $aliasMap @return array<string, string>
generateMethodSynopses
php
awslabs/aws-crt-php
gen_stub.php
https://github.com/awslabs/aws-crt-php/blob/master/gen_stub.php
Apache-2.0
function replaceMethodSynopses(string $targetDirectory, array $funcMap, array $aliasMap): array { $methodSynopses = []; $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($targetDirectory), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($it as $file) { $pathName = $file->getPathName(); if (!preg_match('/\.xml$/i', $pathName)) { continue; } $xml = file_get_contents($pathName); if ($xml === false) { continue; } if (stripos($xml, "<methodsynopsis") === false && stripos($xml, "<constructorsynopsis") === false && stripos($xml, "<destructorsynopsis") === false) { continue; } $replacedXml = preg_replace("/&([A-Za-z0-9._{}%-]+?;)/", "REPLACED-ENTITY-$1", $xml); $doc = new DOMDocument(); $doc->formatOutput = false; $doc->preserveWhiteSpace = true; $doc->validateOnParse = true; $success = $doc->loadXML($replacedXml); if (!$success) { echo "Failed opening $pathName\n"; continue; } $docComparator = new DOMDocument(); $docComparator->preserveWhiteSpace = false; $docComparator->formatOutput = true; $methodSynopsisElements = []; foreach ($doc->getElementsByTagName("constructorsynopsis") as $element) { $methodSynopsisElements[] = $element; } foreach ($doc->getElementsByTagName("destructorsynopsis") as $element) { $methodSynopsisElements[] = $element; } foreach ($doc->getElementsByTagName("methodsynopsis") as $element) { $methodSynopsisElements[] = $element; } foreach ($methodSynopsisElements as $methodSynopsis) { if (!$methodSynopsis instanceof DOMElement) { continue; } $list = $methodSynopsis->getElementsByTagName("methodname"); $item = $list->item(0); if (!$item instanceof DOMElement) { continue; } $funcName = $item->textContent; if (!isset($funcMap[$funcName])) { continue; } $funcInfo = $funcMap[$funcName]; $newMethodSynopsis = $funcInfo->getMethodSynopsisElement($funcMap, $aliasMap, $doc); if ($newMethodSynopsis === null) { continue; } // Retrieve current signature $params = []; $list = $methodSynopsis->getElementsByTagName("methodparam"); foreach ($list as $i => $item) { if (!$item instanceof DOMElement) { continue; } $paramList = $item->getElementsByTagName("parameter"); if ($paramList->count() !== 1) { continue; } $paramName = $paramList->item(0)->textContent; $paramTypes = []; $paramList = $item->getElementsByTagName("type"); foreach ($paramList as $type) { if (!$type instanceof DOMElement) { continue; } $paramTypes[] = $type->textContent; } $params[$paramName] = ["index" => $i, "type" => $paramTypes]; } // Check if there is any change - short circuit if there is not any. $xml1 = $doc->saveXML($methodSynopsis); $xml1 = preg_replace("/&([A-Za-z0-9._{}%-]+?;)/", "REPLACED-ENTITY-$1", $xml1); $docComparator->loadXML($xml1); $xml1 = $docComparator->saveXML(); $methodSynopsis->parentNode->replaceChild($newMethodSynopsis, $methodSynopsis); $xml2 = $doc->saveXML($newMethodSynopsis); $xml2 = preg_replace("/&([A-Za-z0-9._{}%-]+?;)/", "REPLACED-ENTITY-$1", $xml2); $docComparator->loadXML($xml2); $xml2 = $docComparator->saveXML(); if ($xml1 === $xml2) { continue; } // Update parameter references $paramList = $doc->getElementsByTagName("parameter"); /** @var DOMElement $paramElement */ foreach ($paramList as $paramElement) { if ($paramElement->parentNode && $paramElement->parentNode->nodeName === "methodparam") { continue; } $name = $paramElement->textContent; if (!isset($params[$name])) { continue; } $index = $params[$name]["index"]; if (!isset($funcInfo->args[$index])) { continue; } $paramElement->textContent = $funcInfo->args[$index]->name; } // Return the updated XML $replacedXml = $doc->saveXML(); $replacedXml = preg_replace( [ "/REPLACED-ENTITY-([A-Za-z0-9._{}%-]+?;)/", "/<refentry\s+xmlns=\"([a-z0-9.:\/]+)\"\s+xml:id=\"([a-z0-9._-]+)\"\s*>/i", "/<refentry\s+xmlns=\"([a-z0-9.:\/]+)\"\s+xmlns:xlink=\"([a-z0-9.:\/]+)\"\s+xml:id=\"([a-z0-9._-]+)\"\s*>/i", ], [ "&$1", "<refentry xml:id=\"$2\" xmlns=\"$1\">", "<refentry xml:id=\"$3\" xmlns=\"$1\" xmlns:xlink=\"$2\">", ], $replacedXml ); $methodSynopses[$pathName] = $replacedXml; } } return $methodSynopses; }
@param FuncInfo[] $funcMap @param FuncInfo[] $aliasMap @return array<string, string>
replaceMethodSynopses
php
awslabs/aws-crt-php
gen_stub.php
https://github.com/awslabs/aws-crt-php/blob/master/gen_stub.php
Apache-2.0
public static function isLoaded() { return !is_null(self::$impl); }
@return bool whether or not the CRT is currently loaded
isLoaded
php
awslabs/aws-crt-php
src/AWS/CRT/CRT.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/CRT.php
Apache-2.0
public static function isAvailable() { try { new CRT(); return true; } catch (RuntimeException $ex) { return false; } }
@return bool whether or not the CRT is available via one of the possible backends
isAvailable
php
awslabs/aws-crt-php
src/AWS/CRT/CRT.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/CRT.php
Apache-2.0
public static function last_error() { return self::$impl->aws_crt_last_error(); }
@return integer last error code reported within the CRT
last_error
php
awslabs/aws-crt-php
src/AWS/CRT/CRT.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/CRT.php
Apache-2.0
public static function error_str($error) { return self::$impl->aws_crt_error_str((int) $error); }
@param integer $error Error code from the CRT, usually delivered via callback or {@see last_error} @return string Human-readable description of the provided error code
error_str
php
awslabs/aws-crt-php
src/AWS/CRT/CRT.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/CRT.php
Apache-2.0
public static function error_name($error) { return self::$impl->aws_crt_error_name((int) $error); }
@param integer $error Error code from the CRT, usually delivered via callback or {@see last_error} @return string Name/enum identifier for the provided error code
error_name
php
awslabs/aws-crt-php
src/AWS/CRT/CRT.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/CRT.php
Apache-2.0
function event_loop_group_options_set_max_threads($elg_options, $max_threads) { self::$impl->aws_crt_event_loop_group_options_set_max_threads($elg_options, (int)$max_threads); }
@param object $elg_options Pointer to native event_loop_group_options @param integer $max_threads Maximum number of threads to allow the event loop group to use, default: 0/1 per CPU core
event_loop_group_options_set_max_threads
php
awslabs/aws-crt-php
src/AWS/CRT/CRT.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/CRT.php
Apache-2.0
function event_loop_group_new($options) { return self::$impl->aws_crt_event_loop_group_new($options); }
@param object Pointer to event_loop_group_options, {@see event_loop_group_options_new} @return object Pointer to the new event loop group
event_loop_group_new
php
awslabs/aws-crt-php
src/AWS/CRT/CRT.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/CRT.php
Apache-2.0
function aws_credentials_options_new() { return self::$impl->aws_crt_credentials_options_new(); }
return object Pointer to native AWS credentials options
aws_credentials_options_new
php
awslabs/aws-crt-php
src/AWS/CRT/CRT.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/CRT.php
Apache-2.0
function __call($name, $args) { return call_user_func_array($name, $args); }
Forwards any call made on this object to the extension function of the same name with the supplied arguments. Argument type hinting and checking occurs at the CRT wrapper.
__call
php
awslabs/aws-crt-php
src/AWS/CRT/Internal/Extension.php
https://github.com/awslabs/aws-crt-php/blob/master/src/AWS/CRT/Internal/Extension.php
Apache-2.0
public function __construct(array $options = []) { $this->options = array_replace([ 'format' => self::SIMPLE_FORMAT, 'date_format' => self::SIMPLE_DATE, 'colors' => true, 'multiline' => false, 'level_name_format' => '%-9s', 'ignore_empty_context_and_extra' => true, ], $options); if (class_exists(VarCloner::class)) { $this->cloner = new VarCloner(); $this->cloner->addCasters([ '*' => $this->castObject(...), ]); $this->outputBuffer = fopen('php://memory', 'r+'); if ($this->options['multiline']) { $output = $this->outputBuffer; } else { $output = $this->echoLine(...); } $this->dumper = new CliDumper($output, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR); } }
Available options: * format: The format of the outputted log string. The following placeholders are supported: %datetime%, %start_tag%, %level_name%, %end_tag%, %channel%, %message%, %context%, %extra%; * date_format: The format of the outputted date string; * colors: If true, the log string contains ANSI code to add color; * multiline: If false, "context" and "extra" are dumped on one line.
__construct
php
symfony/monolog-bridge
Formatter/ConsoleFormatter.php
https://github.com/symfony/monolog-bridge/blob/master/Formatter/ConsoleFormatter.php
MIT
public function onKernelResponse(ResponseEvent $event): void { if (!$event->isMainRequest()) { return; } if (!preg_match(static::USER_AGENT_REGEX, $event->getRequest()->headers->get('User-Agent', ''))) { self::$sendHeaders = false; $this->headers = []; return; } $this->response = $event->getResponse(); foreach ($this->headers as $header => $content) { $this->response->headers->set($header, $content); } $this->headers = []; }
Adds the headers to the response once it's created.
onKernelResponse
php
symfony/monolog-bridge
Handler/ChromePhpHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/ChromePhpHandler.php
MIT
protected function headersAccepted(): bool { return true; }
Override default behavior since we check it in onKernelResponse.
headersAccepted
php
symfony/monolog-bridge
Handler/ChromePhpHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/ChromePhpHandler.php
MIT
public function __construct( private ?OutputInterface $output = null, bool $bubble = true, array $verbosityLevelMap = [], private array $consoleFormatterOptions = [], ) { parent::__construct(Level::Debug, $bubble); if ($verbosityLevelMap) { $this->verbosityLevelMap = $verbosityLevelMap; } }
@param OutputInterface|null $output The console output to use (the handler remains disabled when passing null until the output is set, e.g. by using console events) @param bool $bubble Whether the messages that are handled can bubble up the stack @param array $verbosityLevelMap Array that maps the OutputInterface verbosity to a minimum logging level (leave empty to use the default mapping)
__construct
php
symfony/monolog-bridge
Handler/ConsoleHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/ConsoleHandler.php
MIT
public function setOutput(OutputInterface $output): void { $this->output = $output; }
Sets the console output to use for printing logs.
setOutput
php
symfony/monolog-bridge
Handler/ConsoleHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/ConsoleHandler.php
MIT
public function onCommand(ConsoleCommandEvent $event): void { $output = $event->getOutput(); if ($output instanceof ConsoleOutputInterface) { $output = $output->getErrorOutput(); } $this->setOutput($output); }
Before a command is executed, the handler gets activated and the console output is set in order to know where to write the logs.
onCommand
php
symfony/monolog-bridge
Handler/ConsoleHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/ConsoleHandler.php
MIT
public function onTerminate(ConsoleTerminateEvent $event): void { $this->close(); }
After a command has been executed, it disables the output.
onTerminate
php
symfony/monolog-bridge
Handler/ConsoleHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/ConsoleHandler.php
MIT
private function updateLevel(): bool { if (null === $this->output) { return false; } $verbosity = $this->output->getVerbosity(); if (isset($this->verbosityLevelMap[$verbosity])) { $this->setLevel($this->verbosityLevelMap[$verbosity]); } else { $this->setLevel(Level::Debug); } return true; }
Updates the logging level based on the verbosity setting of the console output. @return bool Whether the handler is enabled and verbosity is not set to quiet
updateLevel
php
symfony/monolog-bridge
Handler/ConsoleHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/ConsoleHandler.php
MIT
public function onKernelResponse(ResponseEvent $event): void { if (!$event->isMainRequest()) { return; } $request = $event->getRequest(); if (!preg_match('{\bFirePHP/\d+\.\d+\b}', $request->headers->get('User-Agent', '')) && !$request->headers->has('X-FirePHP-Version')) { self::$sendHeaders = false; $this->headers = []; return; } $this->response = $event->getResponse(); foreach ($this->headers as $header => $content) { $this->response->headers->set($header, $content); } $this->headers = []; }
Adds the headers to the response once it's created.
onKernelResponse
php
symfony/monolog-bridge
Handler/FirePHPHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/FirePHPHandler.php
MIT
protected function headersAccepted(): bool { return true; }
Override default behavior since we check the user agent in onKernelResponse.
headersAccepted
php
symfony/monolog-bridge
Handler/FirePHPHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/FirePHPHandler.php
MIT
protected function send(string $content, array $records): void { $this->mailer->send($this->buildMessage($content, $records)); }
Send a mail with the given content. @param string $content formatted email body to be sent @param array $records the array of log records that formed this content
send
php
symfony/monolog-bridge
Handler/MailerHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/MailerHandler.php
MIT
protected function getSubjectFormatter(string $format): FormatterInterface { return new LineFormatter($format); }
Gets the formatter for the Message subject. @param string $format The format of the subject
getSubjectFormatter
php
symfony/monolog-bridge
Handler/MailerHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/MailerHandler.php
MIT
protected function buildMessage(string $content, array $records): Email { if ($this->messageTemplate instanceof Email) { $message = clone $this->messageTemplate; } elseif (\is_callable($this->messageTemplate)) { $message = ($this->messageTemplate)($content, $records); if (!$message instanceof Email) { throw new \InvalidArgumentException(\sprintf('Could not resolve message from a callable. Instance of "%s" is expected.', Email::class)); } } else { throw new \InvalidArgumentException('Could not resolve message as instance of Email or a callable returning it.'); } if ($records) { $subjectFormatter = $this->getSubjectFormatter($message->getSubject()); $message->subject($subjectFormatter->format($this->getHighestRecord($records))); } if ($this->getFormatter() instanceof HtmlFormatter) { if ($message->getHtmlCharset()) { $message->html($content, $message->getHtmlCharset()); } else { $message->html($content); } } else { if ($message->getTextCharset()) { $message->text($content, $message->getTextCharset()); } else { $message->text($content); } } return $message; }
Creates instance of Message to be sent. @param string $content formatted email body to be sent @param array $records Log records that formed the content
buildMessage
php
symfony/monolog-bridge
Handler/MailerHandler.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/MailerHandler.php
MIT
public function __construct( private RequestStack $requestStack, private array $exclusions, private ActivationStrategyInterface $inner, ) { foreach ($exclusions as $exclusion) { if (!\array_key_exists('code', $exclusion)) { throw new \LogicException('An exclusion must have a "code" key.'); } if (!\array_key_exists('urls', $exclusion)) { throw new \LogicException('An exclusion must have a "urls" key.'); } } }
@param array $exclusions each exclusion must have a "code" and "urls" keys
__construct
php
symfony/monolog-bridge
Handler/FingersCrossed/HttpCodeActivationStrategy.php
https://github.com/symfony/monolog-bridge/blob/master/Handler/FingersCrossed/HttpCodeActivationStrategy.php
MIT
function md5($foo) { return (string) $foo; }
Abusing namespaces to make Cycle->id() predictable during tests only!
md5
php
ircmaxell/php-compiler
test/bin/macro_compile.php
https://github.com/ircmaxell/php-compiler/blob/master/test/bin/macro_compile.php
MIT
function render_header() { template('partials/header', [ 'title' => __('Not Found'), 'lead' => __('The page you are looking for no longer exists.'), ]); }
Renders 404 page header. @see resources/templates/index.tpl.php
render_header
php
tonik/theme
404.php
https://github.com/tonik/theme/blob/master/404.php
MIT
function theme($key = null, $parameters = []) { if (null !== $key) { return Theme::getInstance()->get($key, $parameters); } return Theme::getInstance(); }
Gets theme instance. @param string|null $key @param array $parameters @return \Tonik\Gin\Foundation\Theme
theme
php
tonik/theme
app/helpers.php
https://github.com/tonik/theme/blob/master/app/helpers.php
MIT
function config($key = null) { if (null !== $key) { return theme('config')->get($key); } return theme('config'); }
Gets theme config instance. @param string|null $key @return array
config
php
tonik/theme
app/helpers.php
https://github.com/tonik/theme/blob/master/app/helpers.php
MIT
function template($file, $data = []) { $template = new Template(config()); return $template ->setFile($file) ->render($data); }
Renders template file with data. @param string $file Relative path to the template file. @param array $data Dataset for the template. @return void
template
php
tonik/theme
app/helpers.php
https://github.com/tonik/theme/blob/master/app/helpers.php
MIT
function asset($file) { $asset = new Asset(config()); return $asset->setFile($file); }
Gets asset instance. @param string $file Relative file path to the asset file. @return \Tonik\Gin\Asset\Asset
asset
php
tonik/theme
app/helpers.php
https://github.com/tonik/theme/blob/master/app/helpers.php
MIT
function asset_path($file) { return asset($file)->getUri(); }
Gets asset file from public directory. @param string $file Relative file path to the asset file. @return string
asset_path
php
tonik/theme
app/helpers.php
https://github.com/tonik/theme/blob/master/app/helpers.php
MIT
function action_callback() { // Validate nonce token. check_ajax_referer('my_action_nonce', 'nonce'); // Action logic... die(); }
My AJAX action callback. @return void
action_callback
php
tonik/theme
app/Http/ajaxes.php
https://github.com/tonik/theme/blob/master/app/Http/ajaxes.php
MIT
function register_stylesheets() { wp_enqueue_style('app', asset_path('css/app.css')); }
Registers theme stylesheet files. @return void
register_stylesheets
php
tonik/theme
app/Http/assets.php
https://github.com/tonik/theme/blob/master/app/Http/assets.php
MIT
function register_scripts() { wp_enqueue_script('app', asset_path('js/app.js'), ['jquery'], null, true); }
Registers theme script files. @return void
register_scripts
php
tonik/theme
app/Http/assets.php
https://github.com/tonik/theme/blob/master/app/Http/assets.php
MIT
function move_jquery_to_the_footer($wp_scripts) { if (! is_admin()) { $wp_scripts->add_data('jquery', 'group', 1); $wp_scripts->add_data('jquery-core', 'group', 1); $wp_scripts->add_data('jquery-migrate', 'group', 1); } }
Moves front-end jQuery script to the footer. @param \WP_Scripts $wp_scripts @return void
move_jquery_to_the_footer
php
tonik/theme
app/Http/assets.php
https://github.com/tonik/theme/blob/master/app/Http/assets.php
MIT
function show_index_sidebar($status) { if (is_404() || is_page()) { return false; } return $status; }
Hides sidebar on index template on specific views. @see apply_filters('theme/index/sidebar/visibility') @see apply_filters('theme/single/sidebar/visibility')
show_index_sidebar
php
tonik/theme
app/Setup/filters.php
https://github.com/tonik/theme/blob/master/app/Setup/filters.php
MIT
function modify_excerpt_length() { return 60; }
Shortens posts excerpts to 60 words. @return integer
modify_excerpt_length
php
tonik/theme
app/Setup/filters.php
https://github.com/tonik/theme/blob/master/app/Setup/filters.php
MIT
function bind_books_service() { /** * Binds service for retrieving posts of specific post type. * * @param \Tonik\Gin\Foundation\Theme $theme Instance of the service container * @param array $parameters Parameters passed on service resolving * * @return \WP_Post[] */ theme()->bind('books', function (Theme $theme, $parameters) { return new WP_Query([ 'post_type' => 'book', ]); }); }
Service handler for retrieving posts of specific post type. @return void
bind_books_service
php
tonik/theme
app/Setup/services.php
https://github.com/tonik/theme/blob/master/app/Setup/services.php
MIT
function add_theme_supports() { /** * Add support for custom logo. Allow for setting * logo for theme via WordPress customizer. * * @see https://developer.wordpress.org/reference/functions/add_theme_support/#custom-logo */ add_theme_support('custom-logo'); /** * Add support for head <title> tag. By adding `title-tag` support, we * declare that this theme does not use a hard-coded <title> tag in * the document head, and expect WordPress to provide it for us. * * @see https://developer.wordpress.org/reference/functions/add_theme_support/#title-tag */ add_theme_support('title-tag'); /** * Enable support for Post Thumbnails on posts and pages. Note that you * can optionally pass a second argument, $args, with an array of * the Post Types for which you want to enable this feature. * * @see https://developer.wordpress.org/reference/functions/add_theme_support/#post-thumbnails */ add_theme_support('post-thumbnails'); /** * Switch default core markup for search forms, comment forms, comment * lists, gallery, and captions to output valid HTML5 markup. * * @see https://developer.wordpress.org/reference/functions/add_theme_support/#html5 */ add_theme_support('html5', [ 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', ]); }
Adds various theme supports. @return void
add_theme_supports
php
tonik/theme
app/Setup/supports.php
https://github.com/tonik/theme/blob/master/app/Setup/supports.php
MIT
function load_textdomain() { $paths = config('paths'); $directories = config('directories'); load_theme_textdomain(config('textdomain'), "{$paths['directory']}/{$directories['languages']}"); }
Loads theme textdomain language files. @return void
load_textdomain
php
tonik/theme
app/Setup/supports.php
https://github.com/tonik/theme/blob/master/app/Setup/supports.php
MIT
function register_book_post_type() { register_post_type('book', [ 'description' => __('Collection of books.', config('textdomain')), 'public' => true, 'supports' => ['title', 'editor', 'excerpt', 'thumbnail'], 'labels' => [ 'name' => _x('Books', 'post type general name', config('textdomain')), 'singular_name' => _x('Book', 'post type singular name', config('textdomain')), 'menu_name' => _x('Books', 'admin menu', config('textdomain')), 'name_admin_bar' => _x('Book', 'add new on admin bar', config('textdomain')), 'add_new' => _x('Add New', 'book', config('textdomain')), 'add_new_item' => __('Add New Book', config('textdomain')), 'new_item' => __('New Book', config('textdomain')), 'edit_item' => __('Edit Book', config('textdomain')), 'view_item' => __('View Book', config('textdomain')), 'all_items' => __('All Books', config('textdomain')), 'search_items' => __('Search Books', config('textdomain')), 'parent_item_colon' => __('Parent Books:', config('textdomain')), 'not_found' => __('No books found.', config('textdomain')), 'not_found_in_trash' => __('No books found in Trash.', config('textdomain')), ], ]); }
Registers `book` custom post type. @return void
register_book_post_type
php
tonik/theme
app/Structure/posttypes.php
https://github.com/tonik/theme/blob/master/app/Structure/posttypes.php
MIT
function render_button_shortcode($atts, $content) { $attributes = shortcode_atts([ 'href' => '#' ], $atts); ob_start(); template('shortcodes/button', compact('attributes', 'content')); return ob_get_clean(); }
Renders a [button] shortcode. @param array $atts @param string $content @return string
render_button_shortcode
php
tonik/theme
app/Structure/shortcodes.php
https://github.com/tonik/theme/blob/master/app/Structure/shortcodes.php
MIT
function register_widget_areas() { register_sidebar([ 'id' => 'sidebar', 'name' => __('Sidebar', config('textdomain')), 'description' => __('Website sidebar', config('textdomain')), 'before_title' => '<h5>', 'after_title' => '</h5>', ]); }
Registers the widget areas. @return void
register_widget_areas
php
tonik/theme
app/Structure/sidebars.php
https://github.com/tonik/theme/blob/master/app/Structure/sidebars.php
MIT
function render_post_thumbnail() { template(['partials/post/thumbnail', get_post_format()]); }
Renders post thumbnail by its formats. @see resources/templates/index.tpl.php
render_post_thumbnail
php
tonik/theme
app/Structure/templates.php
https://github.com/tonik/theme/blob/master/app/Structure/templates.php
MIT
function render_empty_content() { template(['partials/index/content', 'none']); }
Renders empty post content where there is no posts. @see resources/templates/index.tpl.php
render_empty_content
php
tonik/theme
app/Structure/templates.php
https://github.com/tonik/theme/blob/master/app/Structure/templates.php
MIT
function render_post_content() { template(['partials/post/content', get_post_format()]); }
Renders post contents by its formats. @see resources/templates/single.tpl.php
render_post_content
php
tonik/theme
app/Structure/templates.php
https://github.com/tonik/theme/blob/master/app/Structure/templates.php
MIT
function render_sidebar() { get_sidebar(); }
Renders sidebar content. @uses resources/templates/partials/sidebar.tpl.php @see resources/templates/index.tpl.php @see resources/templates/single.tpl.php
render_sidebar
php
tonik/theme
app/Structure/templates.php
https://github.com/tonik/theme/blob/master/app/Structure/templates.php
MIT
function add_image_sizes() { add_image_size('custom-thumbnail', 800, 600, true); }
Adds new thumbnails image sizes. @return void
add_image_sizes
php
tonik/theme
app/Structure/thumbnails.php
https://github.com/tonik/theme/blob/master/app/Structure/thumbnails.php
MIT
function tonikgin_is_admin_login_or_register_page() { global $pagenow; return is_admin() || in_array($pagenow, ['wp-login.php', 'wp-register.php']); }
Checks if we on the admin, login or register page. @return boolean
tonikgin_is_admin_login_or_register_page
php
tonik/theme
bootstrap/compatibility.php
https://github.com/tonik/theme/blob/master/bootstrap/compatibility.php
MIT
function tonikgin_not_found_notice() { ?> <div class="error notice"> <p> <?php _e("We could not find <a href='//github.com/tonik/gin'><strong>tonik/gin</strong></a> package. You have to install it before using this theme."); ?> </p> </div> <?php }
Outputs error message markup about missing package. @return void
tonikgin_not_found_notice
php
tonik/theme
bootstrap/compatibility.php
https://github.com/tonik/theme/blob/master/bootstrap/compatibility.php
MIT
public function __construct($directory, $format = self::FORMAT_STREAM, Filesystem $fs = null) { $this->directory = $directory; $this->format = $format; $this->fs = $fs ?? new Filesystem(); }
@param string $directory Directory of context @param string $format Format to use when sending the call (stream or tar: string) @param Filesystem $fs filesystem object for cleaning the context directory on destruction
__construct
php
docker-php/docker-php
src/Context/Context.php
https://github.com/docker-php/docker-php/blob/master/src/Context/Context.php
MIT
public function getDirectory() { return $this->directory; }
Get directory of Context. @return string
getDirectory
php
docker-php/docker-php
src/Context/Context.php
https://github.com/docker-php/docker-php/blob/master/src/Context/Context.php
MIT
public function setDirectory($directory): void { $this->directory = $directory; }
Set directory of Context. @param string $directory Targeted directory
setDirectory
php
docker-php/docker-php
src/Context/Context.php
https://github.com/docker-php/docker-php/blob/master/src/Context/Context.php
MIT
public function getDockerfileContent() { return \file_get_contents($this->directory.DIRECTORY_SEPARATOR.'Dockerfile'); }
Return content of Dockerfile of this context. @return string Content of dockerfile
getDockerfileContent
php
docker-php/docker-php
src/Context/Context.php
https://github.com/docker-php/docker-php/blob/master/src/Context/Context.php
MIT
public function toTar() { $process = new Process('/usr/bin/env tar c .', $this->directory); $process->run(); if (!$process->isSuccessful()) { throw new ProcessFailedException($process); } return $process->getOutput(); }
Return the context as a tar archive. @throws \Symfony\Component\Process\Exception\ProcessFailedException @return string Tar content
toTar
php
docker-php/docker-php
src/Context/Context.php
https://github.com/docker-php/docker-php/blob/master/src/Context/Context.php
MIT
public function toStream() { if (!\is_resource($this->process)) { $this->process = \proc_open('/usr/bin/env tar c .', [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, $this->directory); $this->stream = $pipes[1]; } return $this->stream; }
Return a stream for this context. @return resource Stream resource in memory
toStream
php
docker-php/docker-php
src/Context/Context.php
https://github.com/docker-php/docker-php/blob/master/src/Context/Context.php
MIT
public function setCleanup(bool $value): void { $this->cleanup = $value; }
@param bool $value whether to remove the context directory
setCleanup
php
docker-php/docker-php
src/Context/Context.php
https://github.com/docker-php/docker-php/blob/master/src/Context/Context.php
MIT
public function setFormat($format) { $this->format = $format; return $this; }
Sets the format of the Context output. @param string $format @return \Docker\Context\ContextBuilder
setFormat
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function from($from) { $this->commands[] = ['type' => 'FROM', 'image' => $from]; return $this; }
Add a FROM instruction of Dockerfile. @param string $from From which image we start @return \Docker\Context\ContextBuilder
from
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function command($command) { $this->command = $command; return $this; }
Set the CMD instruction in the Dockerfile. @param string $command Command to execute @return \Docker\Context\ContextBuilder
command
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function entrypoint($entrypoint) { $this->entrypoint = $entrypoint; return $this; }
Set the ENTRYPOINT instruction in the Dockerfile. @param string $entrypoint The entrypoint @return \Docker\Context\ContextBuilder
entrypoint
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function add($path, $content) { $this->commands[] = ['type' => 'ADD', 'path' => $path, 'content' => $content]; return $this; }
Add an ADD instruction to Dockerfile. @param string $path Path wanted on the image @param string $content Content of file @return \Docker\Context\ContextBuilder
add
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function addStream($path, $stream) { $this->commands[] = ['type' => 'ADDSTREAM', 'path' => $path, 'stream' => $stream]; return $this; }
Add an ADD instruction to Dockerfile. @param string $path Path wanted on the image @param resource $stream stream that contains file content @return \Docker\Context\ContextBuilder
addStream
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function addFile($path, $file) { $this->commands[] = ['type' => 'ADDFILE', 'path' => $path, 'file' => $file]; return $this; }
Add an ADD instruction to Dockerfile. @param string $path Path wanted on the image @param string $file Source file (or directory) name @return \Docker\Context\ContextBuilder
addFile
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function run($command) { $this->commands[] = ['type' => 'RUN', 'command' => $command]; return $this; }
Add a RUN instruction to Dockerfile. @param string $command Command to run @return \Docker\Context\ContextBuilder
run
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function env($name, $value) { $this->commands[] = ['type' => 'ENV', 'name' => $name, 'value' => $value]; return $this; }
Add a ENV instruction to Dockerfile. @param string $name Name of the environment variable @param string $value Value of the environment variable @return \Docker\Context\ContextBuilder
env
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function copy($from, $to) { $this->commands[] = ['type' => 'COPY', 'from' => $from, 'to' => $to]; return $this; }
Add a COPY instruction to Dockerfile. @param string $from Path of folder or file to copy @param string $to Path of destination @return \Docker\Context\ContextBuilder
copy
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function workdir($workdir) { $this->commands[] = ['type' => 'WORKDIR', 'workdir' => $workdir]; return $this; }
Add a WORKDIR instruction to Dockerfile. @param string $workdir Working directory @return \Docker\Context\ContextBuilder
workdir
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function expose($port) { $this->commands[] = ['type' => 'EXPOSE', 'port' => $port]; return $this; }
Add a EXPOSE instruction to Dockerfile. @param int $port Port to expose @return \Docker\Context\ContextBuilder
expose
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function user($user) { $this->commands[] = ['type' => 'USER', 'user' => $user]; return $this; }
Adds an USER instruction to the Dockerfile. @param string $user User to switch to @return \Docker\Context\ContextBuilder
user
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function volume($volume) { $this->commands[] = ['type' => 'VOLUME', 'volume' => $volume]; return $this; }
Adds a VOLUME instruction to the Dockerfile. @param string $volume Volume path to add @return \Docker\Context\ContextBuilder
volume
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function getContext() { $directory = \sys_get_temp_dir().'/ctb-'.\microtime(); $this->fs->mkdir($directory); $this->write($directory); $result = new Context($directory, $this->format, $this->fs); $result->setCleanup(true); return $result; }
Create context given the state of builder. @return \Docker\Context\Context
getContext
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
private function write($directory): void { $dockerfile = []; // Insert a FROM instruction if the file does not start with one. if (empty($this->commands) || $this->commands[0]['type'] !== 'FROM') { $dockerfile[] = 'FROM base'; } foreach ($this->commands as $command) { switch ($command['type']) { case 'FROM': $dockerfile[] = 'FROM '.$command['image']; break; case 'RUN': $dockerfile[] = 'RUN '.$command['command']; break; case 'ADD': $dockerfile[] = 'ADD '.$this->getFile($directory, $command['content']).' '.$command['path']; break; case 'ADDFILE': $dockerfile[] = 'ADD '.$this->getFileFromDisk($directory, $command['file']).' '.$command['path']; break; case 'ADDSTREAM': $dockerfile[] = 'ADD '.$this->getFileFromStream($directory, $command['stream']).' '.$command['path']; break; case 'COPY': $dockerfile[] = 'COPY '.$command['from'].' '.$command['to']; break; case 'ENV': $dockerfile[] = 'ENV '.$command['name'].' '.$command['value']; break; case 'WORKDIR': $dockerfile[] = 'WORKDIR '.$command['workdir']; break; case 'EXPOSE': $dockerfile[] = 'EXPOSE '.$command['port']; break; case 'VOLUME': $dockerfile[] = 'VOLUME '.$command['volume']; break; case 'USER': $dockerfile[] = 'USER '.$command['user']; break; } } if (!empty($this->entrypoint)) { $dockerfile[] = 'ENTRYPOINT '.$this->entrypoint; } if (!empty($this->command)) { $dockerfile[] = 'CMD '.$this->command; } $this->fs->dumpFile($directory.DIRECTORY_SEPARATOR.'Dockerfile', \implode(PHP_EOL, $dockerfile)); }
Write docker file and associated files in a directory. @param string $directory Target directory @void
write
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
private function getFile($directory, $content) { $hash = \md5($content); if (!\array_key_exists($hash, $this->files)) { $file = \tempnam($directory, ''); $this->fs->dumpFile($file, $content); $this->files[$hash] = \basename($file); } return $this->files[$hash]; }
Generate a file in a directory. @param string $directory Targeted directory @param string $content Content of file @return string Name of file generated
getFile
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
private function getFileFromStream($directory, $stream) { $file = \tempnam($directory, ''); $target = \fopen($file, 'w'); if (0 === \stream_copy_to_stream($stream, $target)) { throw new \RuntimeException('Failed to write stream to file'); } \fclose($target); return \basename($file); }
Generated a file in a directory from a stream. @param string $directory Targeted directory @param resource $stream Stream containing file contents @return string Name of file generated
getFileFromStream
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
private function getFileFromDisk($directory, $source) { $hash = 'DISK-'.\md5(\realpath($source)); if (!\array_key_exists($hash, $this->files)) { // Check if source is a directory or a file. if (\is_dir($source)) { $this->fs->mirror($source, $directory.'/'.$hash, null, ['copy_on_windows' => true]); } else { $this->fs->copy($source, $directory.'/'.$hash); } $this->files[$hash] = $hash; } return $this->files[$hash]; }
Generated a file in a directory from an existing file. @param string $directory Targeted directory @param string $source Path to the source file @return string Name of file generated
getFileFromDisk
php
docker-php/docker-php
src/Context/ContextBuilder.php
https://github.com/docker-php/docker-php/blob/master/src/Context/ContextBuilder.php
MIT
public function onFrame(callable $onNewFrame): void { $this->onNewFrameCallables[] = $onNewFrame; }
Called when there is a new frame from the stream. @param callable $onNewFrame
onFrame
php
docker-php/docker-php
src/Stream/ArtaxCallbackStream.php
https://github.com/docker-php/docker-php/blob/master/src/Stream/ArtaxCallbackStream.php
MIT
private function transformChunk(string $chunk) { if (null === $this->chunkTransformer) { return $chunk; } return \call_user_func($this->chunkTransformer, $chunk); }
Transform stream chunks if required. @param string $chunk @return mixed The raw chunk or the transformed chunk
transformChunk
php
docker-php/docker-php
src/Stream/ArtaxCallbackStream.php
https://github.com/docker-php/docker-php/blob/master/src/Stream/ArtaxCallbackStream.php
MIT
public function write($data): void { $rand = \random_int(0, 28); $frame = [ 'fin' => 1, 'rsv1' => 0, 'rsv2' => 0, 'rsv3' => 0, 'opcode' => 1, // We always send text 'mask' => 1, 'len' => \strlen($data), 'mask_key' => \substr(\md5(\uniqid()), $rand, 4), 'data' => $data, ]; if (1 === $frame['mask']) { for ($i = 0; $i < $frame['len']; ++$i) { $frame['data'][$i] = \chr(\ord($frame['data'][$i]) ^ \ord($frame['mask_key'][$i % 4])); } } if ($frame['len'] > 2 ** 16) { $len = 127; } elseif ($frame['len'] > 125) { $len = 126; } else { $len = $frame['len']; } $firstByte = ($frame['fin'] << 7) | (($frame['rsv1'] << 7) >> 1) | (($frame['rsv2'] << 7) >> 2) | (($frame['rsv3'] << 7) >> 3) | (($frame['opcode'] << 4) >> 4); $secondByte = ($frame['mask'] << 7) | (($len << 1) >> 1); $this->socketWrite(\chr($firstByte)); $this->socketWrite(\chr($secondByte)); if (126 === $len) { $this->socketWrite(\pack('n', $frame['len'])); } elseif (127 === $len) { $higher = $frame['len'] >> 32; $lower = ($frame['len'] << 32) >> 32; $this->socketWrite(\pack('N', $higher)); $this->socketWrite(\pack('N', $lower)); } if (1 === $frame['mask']) { $this->socketWrite($frame['mask_key']); } $this->socketWrite($frame['data']); }
Send input to the container. @param string $data Data to send
write
php
docker-php/docker-php
src/Stream/AttachWebsocketStream.php
https://github.com/docker-php/docker-php/blob/master/src/Stream/AttachWebsocketStream.php
MIT
public function read($waitTime = 0, $waitMicroTime = 200000, $getFrame = false) { if (!\is_resource($this->socket) || \feof($this->socket)) { return null; } $read = [$this->socket]; $write = null; $expect = null; if (0 === \stream_select($read, $write, $expect, $waitTime, $waitMicroTime)) { return false; } $firstByte = $this->socketRead(1); $frame = []; $firstByte = \ord($firstByte); $secondByte = \ord($this->socketRead(1)); // First byte decoding $frame['fin'] = ($firstByte & 128) >> 7; $frame['rsv1'] = ($firstByte & 64) >> 6; $frame['rsv2'] = ($firstByte & 32) >> 5; $frame['rsv3'] = ($firstByte & 16) >> 4; $frame['opcode'] = ($firstByte & 15); // Second byte decoding $frame['mask'] = ($secondByte & 128) >> 7; $frame['len'] = ($secondByte & 127); // Get length of the frame if (126 === $frame['len']) { $frame['len'] = \unpack('n', $this->socketRead(2))[1]; } elseif (127 === $frame['len']) { list($higher, $lower) = \array_values(\unpack('N2', $this->socketRead(8))); $frame['len'] = ($higher << 32) | $lower; } // Get the mask key if needed if (1 === $frame['mask']) { $frame['mask_key'] = $this->socketRead(4); } $frame['data'] = $this->socketRead($frame['len']); // Decode data if needed if (1 === $frame['mask']) { for ($i = 0; $i < $frame['len']; ++$i) { $frame['data'][$i] = \chr(\ord($frame['data'][$i]) ^ \ord($frame['mask_key'][$i % 4])); } } if ($getFrame) { return $frame; } return (string) $frame['data']; }
Block until it receive a frame from websocket or return null if no more connexion. @param int $waitTime Time to wait in seconds before return false @param int $waitMicroTime Time to wait in microseconds before return false @param bool $getFrame Whether to return the frame of websocket or only the data @return null|false|string|array Null for socket not available, false for no message, string for the last message and the frame array if $getFrame is set to true
read
php
docker-php/docker-php
src/Stream/AttachWebsocketStream.php
https://github.com/docker-php/docker-php/blob/master/src/Stream/AttachWebsocketStream.php
MIT
private function socketRead($length) { $read = ''; do { $read .= \fread($this->socket, $length - \strlen($read)); } while (\strlen($read) < $length && !\feof($this->socket)); return $read; }
Force to have something of the expected size (block). @param $length @return string
socketRead
php
docker-php/docker-php
src/Stream/AttachWebsocketStream.php
https://github.com/docker-php/docker-php/blob/master/src/Stream/AttachWebsocketStream.php
MIT
private function socketWrite($data) { return \fwrite($this->socket, $data); }
Write to the socket. @param $data @return int
socketWrite
php
docker-php/docker-php
src/Stream/AttachWebsocketStream.php
https://github.com/docker-php/docker-php/blob/master/src/Stream/AttachWebsocketStream.php
MIT
public function onFrame(callable $onNewFrame): void { $this->onNewFrameCallables[] = $onNewFrame; }
Called when there is a new frame from the stream. @param callable $onNewFrame
onFrame
php
docker-php/docker-php
src/Stream/CallbackStream.php
https://github.com/docker-php/docker-php/blob/master/src/Stream/CallbackStream.php
MIT