repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
wardrobecms/core-archived
src/Wardrobe/Core/WardrobeServiceProvider.php
WardrobeServiceProvider.setConnection
public function setConnection() { $connection = Config::get('core::database.default'); if ($connection !== 'default') { $wardrobeConfig = Config::get('core::database.connections.'.$connection); } else { $connection = Config::get('database.default'); $wardrobeConfig = Config::get('database.connections.'.$connection); } Config::set('database.connections.wardrobe', $wardrobeConfig); }
php
public function setConnection() { $connection = Config::get('core::database.default'); if ($connection !== 'default') { $wardrobeConfig = Config::get('core::database.connections.'.$connection); } else { $connection = Config::get('database.default'); $wardrobeConfig = Config::get('database.connections.'.$connection); } Config::set('database.connections.wardrobe', $wardrobeConfig); }
[ "public", "function", "setConnection", "(", ")", "{", "$", "connection", "=", "Config", "::", "get", "(", "'core::database.default'", ")", ";", "if", "(", "$", "connection", "!==", "'default'", ")", "{", "$", "wardrobeConfig", "=", "Config", "::", "get", "...
Set up the db connection @return void
[ "Set", "up", "the", "db", "connection" ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/WardrobeServiceProvider.php#L91-L106
skrz/meta
gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php
EnumDescriptorProtoMeta.create
public static function create() { switch (func_num_args()) { case 0: return new EnumDescriptorProto(); case 1: return new EnumDescriptorProto(func_get_arg(0)); case 2: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1)); case 3: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2)); case 4: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3)); case 5: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4)); case 6: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5)); case 7: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6)); case 8: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6), func_get_arg(7)); default: throw new \InvalidArgumentException('More than 8 arguments supplied, please be reasonable.'); } }
php
public static function create() { switch (func_num_args()) { case 0: return new EnumDescriptorProto(); case 1: return new EnumDescriptorProto(func_get_arg(0)); case 2: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1)); case 3: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2)); case 4: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3)); case 5: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4)); case 6: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5)); case 7: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6)); case 8: return new EnumDescriptorProto(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6), func_get_arg(7)); default: throw new \InvalidArgumentException('More than 8 arguments supplied, please be reasonable.'); } }
[ "public", "static", "function", "create", "(", ")", "{", "switch", "(", "func_num_args", "(", ")", ")", "{", "case", "0", ":", "return", "new", "EnumDescriptorProto", "(", ")", ";", "case", "1", ":", "return", "new", "EnumDescriptorProto", "(", "func_get_a...
Creates new instance of \Google\Protobuf\EnumDescriptorProto @throws \InvalidArgumentException @return EnumDescriptorProto
[ "Creates", "new", "instance", "of", "\\", "Google", "\\", "Protobuf", "\\", "EnumDescriptorProto" ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php#L59-L83
skrz/meta
gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php
EnumDescriptorProtoMeta.reset
public static function reset($object) { if (!($object instanceof EnumDescriptorProto)) { throw new \InvalidArgumentException('You have to pass object of class Google\Protobuf\EnumDescriptorProto.'); } $object->name = NULL; $object->value = NULL; $object->options = NULL; }
php
public static function reset($object) { if (!($object instanceof EnumDescriptorProto)) { throw new \InvalidArgumentException('You have to pass object of class Google\Protobuf\EnumDescriptorProto.'); } $object->name = NULL; $object->value = NULL; $object->options = NULL; }
[ "public", "static", "function", "reset", "(", "$", "object", ")", "{", "if", "(", "!", "(", "$", "object", "instanceof", "EnumDescriptorProto", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'You have to pass object of class Google\\Protobuf\...
Resets properties of \Google\Protobuf\EnumDescriptorProto to default values @param EnumDescriptorProto $object @throws \InvalidArgumentException @return void
[ "Resets", "properties", "of", "\\", "Google", "\\", "Protobuf", "\\", "EnumDescriptorProto", "to", "default", "values" ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php#L96-L104
skrz/meta
gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php
EnumDescriptorProtoMeta.hash
public static function hash($object, $algoOrCtx = 'md5', $raw = FALSE) { if (is_string($algoOrCtx)) { $ctx = hash_init($algoOrCtx); } else { $ctx = $algoOrCtx; } if (isset($object->name)) { hash_update($ctx, 'name'); hash_update($ctx, (string)$object->name); } if (isset($object->value)) { hash_update($ctx, 'value'); foreach ($object->value instanceof \Traversable ? $object->value : (array)$object->value as $v0) { EnumValueDescriptorProtoMeta::hash($v0, $ctx); } } if (isset($object->options)) { hash_update($ctx, 'options'); EnumOptionsMeta::hash($object->options, $ctx); } if (is_string($algoOrCtx)) { return hash_final($ctx, $raw); } else { return null; } }
php
public static function hash($object, $algoOrCtx = 'md5', $raw = FALSE) { if (is_string($algoOrCtx)) { $ctx = hash_init($algoOrCtx); } else { $ctx = $algoOrCtx; } if (isset($object->name)) { hash_update($ctx, 'name'); hash_update($ctx, (string)$object->name); } if (isset($object->value)) { hash_update($ctx, 'value'); foreach ($object->value instanceof \Traversable ? $object->value : (array)$object->value as $v0) { EnumValueDescriptorProtoMeta::hash($v0, $ctx); } } if (isset($object->options)) { hash_update($ctx, 'options'); EnumOptionsMeta::hash($object->options, $ctx); } if (is_string($algoOrCtx)) { return hash_final($ctx, $raw); } else { return null; } }
[ "public", "static", "function", "hash", "(", "$", "object", ",", "$", "algoOrCtx", "=", "'md5'", ",", "$", "raw", "=", "FALSE", ")", "{", "if", "(", "is_string", "(", "$", "algoOrCtx", ")", ")", "{", "$", "ctx", "=", "hash_init", "(", "$", "algoOrC...
Computes hash of \Google\Protobuf\EnumDescriptorProto @param object $object @param string|resource $algoOrCtx @param bool $raw @return string|void
[ "Computes", "hash", "of", "\\", "Google", "\\", "Protobuf", "\\", "EnumDescriptorProto" ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php#L116-L146
skrz/meta
gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php
EnumDescriptorProtoMeta.fromProtobuf
public static function fromProtobuf($input, $object = NULL, &$start = 0, $end = NULL) { if ($object === null) { $object = new EnumDescriptorProto(); } if ($end === null) { $end = strlen($input); } while ($start < $end) { $tag = Binary::decodeVarint($input, $start); $wireType = $tag & 0x7; $number = $tag >> 3; switch ($number) { case 1: if ($wireType !== 2) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 2.', $number); } $length = Binary::decodeVarint($input, $start); $expectedStart = $start + $length; if ($expectedStart > $end) { throw new ProtobufException('Not enough data.'); } $object->name = substr($input, $start, $length); $start += $length; if ($start !== $expectedStart) { throw new ProtobufException('Unexpected start. Expected ' . $expectedStart . ', got ' . $start . '.', $number); } break; case 2: if ($wireType !== 2) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 2.', $number); } if (!(isset($object->value) && is_array($object->value))) { $object->value = array(); } $length = Binary::decodeVarint($input, $start); $expectedStart = $start + $length; if ($expectedStart > $end) { throw new ProtobufException('Not enough data.'); } $object->value[] = EnumValueDescriptorProtoMeta::fromProtobuf($input, null, $start, $start + $length); if ($start !== $expectedStart) { throw new ProtobufException('Unexpected start. Expected ' . $expectedStart . ', got ' . $start . '.', $number); } break; case 3: if ($wireType !== 2) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 2.', $number); } $length = Binary::decodeVarint($input, $start); $expectedStart = $start + $length; if ($expectedStart > $end) { throw new ProtobufException('Not enough data.'); } $object->options = EnumOptionsMeta::fromProtobuf($input, null, $start, $start + $length); if ($start !== $expectedStart) { throw new ProtobufException('Unexpected start. Expected ' . $expectedStart . ', got ' . $start . '.', $number); } break; default: switch ($wireType) { case 0: Binary::decodeVarint($input, $start); break; case 1: $start += 8; break; case 2: $start += Binary::decodeVarint($input, $start); break; case 5: $start += 4; break; default: throw new ProtobufException('Unexpected wire type ' . $wireType . '.', $number); } } } return $object; }
php
public static function fromProtobuf($input, $object = NULL, &$start = 0, $end = NULL) { if ($object === null) { $object = new EnumDescriptorProto(); } if ($end === null) { $end = strlen($input); } while ($start < $end) { $tag = Binary::decodeVarint($input, $start); $wireType = $tag & 0x7; $number = $tag >> 3; switch ($number) { case 1: if ($wireType !== 2) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 2.', $number); } $length = Binary::decodeVarint($input, $start); $expectedStart = $start + $length; if ($expectedStart > $end) { throw new ProtobufException('Not enough data.'); } $object->name = substr($input, $start, $length); $start += $length; if ($start !== $expectedStart) { throw new ProtobufException('Unexpected start. Expected ' . $expectedStart . ', got ' . $start . '.', $number); } break; case 2: if ($wireType !== 2) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 2.', $number); } if (!(isset($object->value) && is_array($object->value))) { $object->value = array(); } $length = Binary::decodeVarint($input, $start); $expectedStart = $start + $length; if ($expectedStart > $end) { throw new ProtobufException('Not enough data.'); } $object->value[] = EnumValueDescriptorProtoMeta::fromProtobuf($input, null, $start, $start + $length); if ($start !== $expectedStart) { throw new ProtobufException('Unexpected start. Expected ' . $expectedStart . ', got ' . $start . '.', $number); } break; case 3: if ($wireType !== 2) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 2.', $number); } $length = Binary::decodeVarint($input, $start); $expectedStart = $start + $length; if ($expectedStart > $end) { throw new ProtobufException('Not enough data.'); } $object->options = EnumOptionsMeta::fromProtobuf($input, null, $start, $start + $length); if ($start !== $expectedStart) { throw new ProtobufException('Unexpected start. Expected ' . $expectedStart . ', got ' . $start . '.', $number); } break; default: switch ($wireType) { case 0: Binary::decodeVarint($input, $start); break; case 1: $start += 8; break; case 2: $start += Binary::decodeVarint($input, $start); break; case 5: $start += 4; break; default: throw new ProtobufException('Unexpected wire type ' . $wireType . '.', $number); } } } return $object; }
[ "public", "static", "function", "fromProtobuf", "(", "$", "input", ",", "$", "object", "=", "NULL", ",", "&", "$", "start", "=", "0", ",", "$", "end", "=", "NULL", ")", "{", "if", "(", "$", "object", "===", "null", ")", "{", "$", "object", "=", ...
Creates \Google\Protobuf\EnumDescriptorProto object from serialized Protocol Buffers message. @param string $input @param EnumDescriptorProto $object @param int $start @param int $end @throws \Exception @return EnumDescriptorProto
[ "Creates", "\\", "Google", "\\", "Protobuf", "\\", "EnumDescriptorProto", "object", "from", "serialized", "Protocol", "Buffers", "message", "." ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php#L161-L243
skrz/meta
gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php
EnumDescriptorProtoMeta.toProtobuf
public static function toProtobuf($object, $filter = NULL) { $output = ''; if (isset($object->name) && ($filter === null || isset($filter['name']))) { $output .= "\x0a"; $output .= Binary::encodeVarint(strlen($object->name)); $output .= $object->name; } if (isset($object->value) && ($filter === null || isset($filter['value']))) { foreach ($object->value instanceof \Traversable ? $object->value : (array)$object->value as $k => $v) { $output .= "\x12"; $buffer = EnumValueDescriptorProtoMeta::toProtobuf($v, $filter === null ? null : $filter['value']); $output .= Binary::encodeVarint(strlen($buffer)); $output .= $buffer; } } if (isset($object->options) && ($filter === null || isset($filter['options']))) { $output .= "\x1a"; $buffer = EnumOptionsMeta::toProtobuf($object->options, $filter === null ? null : $filter['options']); $output .= Binary::encodeVarint(strlen($buffer)); $output .= $buffer; } return $output; }
php
public static function toProtobuf($object, $filter = NULL) { $output = ''; if (isset($object->name) && ($filter === null || isset($filter['name']))) { $output .= "\x0a"; $output .= Binary::encodeVarint(strlen($object->name)); $output .= $object->name; } if (isset($object->value) && ($filter === null || isset($filter['value']))) { foreach ($object->value instanceof \Traversable ? $object->value : (array)$object->value as $k => $v) { $output .= "\x12"; $buffer = EnumValueDescriptorProtoMeta::toProtobuf($v, $filter === null ? null : $filter['value']); $output .= Binary::encodeVarint(strlen($buffer)); $output .= $buffer; } } if (isset($object->options) && ($filter === null || isset($filter['options']))) { $output .= "\x1a"; $buffer = EnumOptionsMeta::toProtobuf($object->options, $filter === null ? null : $filter['options']); $output .= Binary::encodeVarint(strlen($buffer)); $output .= $buffer; } return $output; }
[ "public", "static", "function", "toProtobuf", "(", "$", "object", ",", "$", "filter", "=", "NULL", ")", "{", "$", "output", "=", "''", ";", "if", "(", "isset", "(", "$", "object", "->", "name", ")", "&&", "(", "$", "filter", "===", "null", "||", ...
Serialized \Google\Protobuf\EnumDescriptorProto to Protocol Buffers message. @param EnumDescriptorProto $object @param array $filter @throws \Exception @return string
[ "Serialized", "\\", "Google", "\\", "Protobuf", "\\", "EnumDescriptorProto", "to", "Protocol", "Buffers", "message", "." ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/Meta/EnumDescriptorProtoMeta.php#L256-L283
jkphl/dom-factory
src/Domfactory/Ports/Dom.php
Dom.createFromUri
public static function createFromUri($url, array $options = []) { return extension_loaded('curl') ? self::createViaHttpClient($url, $options) : self::createViaStreamWrapper($url, $options); }
php
public static function createFromUri($url, array $options = []) { return extension_loaded('curl') ? self::createViaHttpClient($url, $options) : self::createViaStreamWrapper($url, $options); }
[ "public", "static", "function", "createFromUri", "(", "$", "url", ",", "array", "$", "options", "=", "[", "]", ")", "{", "return", "extension_loaded", "(", "'curl'", ")", "?", "self", "::", "createViaHttpClient", "(", "$", "url", ",", "$", "options", ")"...
Create a DOM document from a URI @param string $url HTTP / HTTPS URL @param array $options Connection options @return \DOMDocument DOM document @api
[ "Create", "a", "DOM", "document", "from", "a", "URI" ]
train
https://github.com/jkphl/dom-factory/blob/460595b73b214510b29f483d61358296d2825143/src/Domfactory/Ports/Dom.php#L57-L61
jkphl/dom-factory
src/Domfactory/Ports/Dom.php
Dom.createFromFile
public static function createFromFile($file) { // If the file is not readable if (!is_readable($file)) { throw new InvalidArgumentException( sprintf(InvalidArgumentException::INVALID_FILE_STR, $file), InvalidArgumentException::INVALID_FILE ); } return self::createFromString(file_get_contents($file)); }
php
public static function createFromFile($file) { // If the file is not readable if (!is_readable($file)) { throw new InvalidArgumentException( sprintf(InvalidArgumentException::INVALID_FILE_STR, $file), InvalidArgumentException::INVALID_FILE ); } return self::createFromString(file_get_contents($file)); }
[ "public", "static", "function", "createFromFile", "(", "$", "file", ")", "{", "// If the file is not readable", "if", "(", "!", "is_readable", "(", "$", "file", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "InvalidArgumentExcepti...
Create a DOM document from a file @param string $file File @return \DOMDocument DOM document @throws InvalidArgumentException If the file is not readable @api
[ "Create", "a", "DOM", "document", "from", "a", "file" ]
train
https://github.com/jkphl/dom-factory/blob/460595b73b214510b29f483d61358296d2825143/src/Domfactory/Ports/Dom.php#L71-L82
yeephp/yeephp
Yee/Middleware/MethodOverride.php
MethodOverride.call
public function call() { $env = $this->app->environment(); if (isset($env['HTTP_X_HTTP_METHOD_OVERRIDE'])) { // Header commonly used by Backbone.js and others $env['yee.method_override.original_method'] = $env['REQUEST_METHOD']; $env['REQUEST_METHOD'] = strtoupper($env['HTTP_X_HTTP_METHOD_OVERRIDE']); } elseif (isset($env['REQUEST_METHOD']) && $env['REQUEST_METHOD'] === 'POST') { // HTML Form Override $req = new \Yee\Http\Request($env); $method = $req->post($this->settings['key']); if ($method) { $env['yee.method_override.original_method'] = $env['REQUEST_METHOD']; $env['REQUEST_METHOD'] = strtoupper($method); } } $this->next->call(); }
php
public function call() { $env = $this->app->environment(); if (isset($env['HTTP_X_HTTP_METHOD_OVERRIDE'])) { // Header commonly used by Backbone.js and others $env['yee.method_override.original_method'] = $env['REQUEST_METHOD']; $env['REQUEST_METHOD'] = strtoupper($env['HTTP_X_HTTP_METHOD_OVERRIDE']); } elseif (isset($env['REQUEST_METHOD']) && $env['REQUEST_METHOD'] === 'POST') { // HTML Form Override $req = new \Yee\Http\Request($env); $method = $req->post($this->settings['key']); if ($method) { $env['yee.method_override.original_method'] = $env['REQUEST_METHOD']; $env['REQUEST_METHOD'] = strtoupper($method); } } $this->next->call(); }
[ "public", "function", "call", "(", ")", "{", "$", "env", "=", "$", "this", "->", "app", "->", "environment", "(", ")", ";", "if", "(", "isset", "(", "$", "env", "[", "'HTTP_X_HTTP_METHOD_OVERRIDE'", "]", ")", ")", "{", "// Header commonly used by Backbone....
Call Implements Yee middleware interface. This method is invoked and passed an array of environment variables. This middleware inspects the environment variables for the HTTP method override parameter; if found, this middleware modifies the environment settings so downstream middleware and/or the Yee application will treat the request with the desired HTTP method. @return array[status, header, body]
[ "Call" ]
train
https://github.com/yeephp/yeephp/blob/6107f60ceaf0811a6550872bd669580ac282cb1f/Yee/Middleware/MethodOverride.php#L76-L93
budde377/Part
lib/model/page/CurrentPageStrategyImpl.php
CurrentPageStrategyImpl.getCurrentPagePath
public function getCurrentPagePath() { if ($this->currentPagePath != null) { return $this->currentPagePath; } $pageOrderArray = $this->pageOrder->getPageOrder(); $path = $this->GETValueOfIndexIfSetElseDefault('page', false); if (!empty($path) && !empty($pagePath = $this->getPathArrayFromString($path, $pageOrderArray))) { return $this->currentPagePath = $pagePath; } if (!empty($pageOrderArray) && empty($path)) { return $this->currentPagePath = [array_shift($pageOrderArray)]; } return $this->currentPagePath = [new NotFoundPageImpl($this->container)]; }
php
public function getCurrentPagePath() { if ($this->currentPagePath != null) { return $this->currentPagePath; } $pageOrderArray = $this->pageOrder->getPageOrder(); $path = $this->GETValueOfIndexIfSetElseDefault('page', false); if (!empty($path) && !empty($pagePath = $this->getPathArrayFromString($path, $pageOrderArray))) { return $this->currentPagePath = $pagePath; } if (!empty($pageOrderArray) && empty($path)) { return $this->currentPagePath = [array_shift($pageOrderArray)]; } return $this->currentPagePath = [new NotFoundPageImpl($this->container)]; }
[ "public", "function", "getCurrentPagePath", "(", ")", "{", "if", "(", "$", "this", "->", "currentPagePath", "!=", "null", ")", "{", "return", "$", "this", "->", "currentPagePath", ";", "}", "$", "pageOrderArray", "=", "$", "this", "->", "pageOrder", "->", ...
Will return the path to the current page as an array of Page's @return array
[ "Will", "return", "the", "path", "to", "the", "current", "page", "as", "an", "array", "of", "Page", "s" ]
train
https://github.com/budde377/Part/blob/9ab5ce43dd809f9c563040ae0f7dcb7f56a52c5d/lib/model/page/CurrentPageStrategyImpl.php#L36-L57
baleen/migrations
src/Service/DomainBus/Migrate/Single/SingleHandler.php
SingleHandler.handle
public function handle(SingleCommand $command) { /** @var MigrationRunner $runner */ $runner = $this->getRunner(); $runner = $runner->withContext($command->getContext()); $event = $runner->run( $command->getTarget(), $command->getOptions() ); return $command->getVersionRepository()->update($event->getTarget()); }
php
public function handle(SingleCommand $command) { /** @var MigrationRunner $runner */ $runner = $this->getRunner(); $runner = $runner->withContext($command->getContext()); $event = $runner->run( $command->getTarget(), $command->getOptions() ); return $command->getVersionRepository()->update($event->getTarget()); }
[ "public", "function", "handle", "(", "SingleCommand", "$", "command", ")", "{", "/** @var MigrationRunner $runner */", "$", "runner", "=", "$", "this", "->", "getRunner", "(", ")", ";", "$", "runner", "=", "$", "runner", "->", "withContext", "(", "$", "comma...
handle @param SingleCommand $command @return DeltaInterface
[ "handle" ]
train
https://github.com/baleen/migrations/blob/cfc8c439858cf4f0d4119af9eb67de493da8d95c/src/Service/DomainBus/Migrate/Single/SingleHandler.php#L54-L64
yeephp/yeephp
Yee/Views/Twig.php
Twig.getInstance
public function getInstance() { if (!$this->parserInstance) { /** * Check if Twig_Autoloader class exists * otherwise include it. */ if (!class_exists('\Twig_Autoloader')) { require_once $this->parserDirectory . '/Autoloader.php'; } \Twig_Autoloader::register(); $loader = new \Twig_Loader_Filesystem($this->getTemplateDirs()); $this->parserInstance = new \Twig_Environment( $loader, $this->parserOptions ); foreach ($this->parserExtensions as $ext) { $extension = is_object($ext) ? $ext : new $ext; $this->parserInstance->addExtension($extension); } } return $this->parserInstance; }
php
public function getInstance() { if (!$this->parserInstance) { /** * Check if Twig_Autoloader class exists * otherwise include it. */ if (!class_exists('\Twig_Autoloader')) { require_once $this->parserDirectory . '/Autoloader.php'; } \Twig_Autoloader::register(); $loader = new \Twig_Loader_Filesystem($this->getTemplateDirs()); $this->parserInstance = new \Twig_Environment( $loader, $this->parserOptions ); foreach ($this->parserExtensions as $ext) { $extension = is_object($ext) ? $ext : new $ext; $this->parserInstance->addExtension($extension); } } return $this->parserInstance; }
[ "public", "function", "getInstance", "(", ")", "{", "if", "(", "!", "$", "this", "->", "parserInstance", ")", "{", "/**\n * Check if Twig_Autoloader class exists\n * otherwise include it.\n */", "if", "(", "!", "class_exists", "(", "'\\Tw...
Creates new TwigEnvironment if it doesn't already exist, and returns it. @return \Twig_Environment
[ "Creates", "new", "TwigEnvironment", "if", "it", "doesn", "t", "already", "exist", "and", "returns", "it", "." ]
train
https://github.com/yeephp/yeephp/blob/6107f60ceaf0811a6550872bd669580ac282cb1f/Yee/Views/Twig.php#L109-L135
joetannenbaum/phpushbullet
src/Request/PushFile.php
PushFile.getFileType
protected function getFileType($file_url) { $file_info = (new Client())->head($file_url); $file_type = $file_info->getHeader('content-type'); if (is_array($file_type)) { return reset($file_type); } return $file_type; }
php
protected function getFileType($file_url) { $file_info = (new Client())->head($file_url); $file_type = $file_info->getHeader('content-type'); if (is_array($file_type)) { return reset($file_type); } return $file_type; }
[ "protected", "function", "getFileType", "(", "$", "file_url", ")", "{", "$", "file_info", "=", "(", "new", "Client", "(", ")", ")", "->", "head", "(", "$", "file_url", ")", ";", "$", "file_type", "=", "$", "file_info", "->", "getHeader", "(", "'content...
Get the file type based on the file url @param string $file_url @return string
[ "Get", "the", "file", "type", "based", "on", "the", "file", "url" ]
train
https://github.com/joetannenbaum/phpushbullet/blob/df138ebb3adebcddade282be478c0d2d6ebffb3e/src/Request/PushFile.php#L33-L43
kss-php/kss-php
lib/Modifier.php
Modifier.parseExtend
protected function parseExtend($name) { $this->setExtendedClass(null); $nameParts = explode('@extend', $name); $name = trim($nameParts[0]); if (count($nameParts) > 1) { $this->setExtendedClass($nameParts[1]); } return $name; }
php
protected function parseExtend($name) { $this->setExtendedClass(null); $nameParts = explode('@extend', $name); $name = trim($nameParts[0]); if (count($nameParts) > 1) { $this->setExtendedClass($nameParts[1]); } return $name; }
[ "protected", "function", "parseExtend", "(", "$", "name", ")", "{", "$", "this", "->", "setExtendedClass", "(", "null", ")", ";", "$", "nameParts", "=", "explode", "(", "'@extend'", ",", "$", "name", ")", ";", "$", "name", "=", "trim", "(", "$", "nam...
Checks the name for any extend notations and parses that information off and stores it in the $this->extendedClass @param string $name @return $name
[ "Checks", "the", "name", "for", "any", "extend", "notations", "and", "parses", "that", "information", "off", "and", "stores", "it", "in", "the", "$this", "-", ">", "extendedClass" ]
train
https://github.com/kss-php/kss-php/blob/5431bfb3c3708cfedb6a95fc3413181287d1f776/lib/Modifier.php#L122-L133
kss-php/kss-php
lib/Modifier.php
Modifier.getExtendedClassName
public function getExtendedClassName() { if ($this->getExtendedClass() === null) { return ''; } $name = str_replace('%', ' ', $this->getExtendedClass()); $name = str_replace('.', ' ', $name); $name = str_replace(':', ' pseudo-class-', $name); return trim($name); }
php
public function getExtendedClassName() { if ($this->getExtendedClass() === null) { return ''; } $name = str_replace('%', ' ', $this->getExtendedClass()); $name = str_replace('.', ' ', $name); $name = str_replace(':', ' pseudo-class-', $name); return trim($name); }
[ "public", "function", "getExtendedClassName", "(", ")", "{", "if", "(", "$", "this", "->", "getExtendedClass", "(", ")", "===", "null", ")", "{", "return", "''", ";", "}", "$", "name", "=", "str_replace", "(", "'%'", ",", "' '", ",", "$", "this", "->...
Returns the class name for the extended class @return string
[ "Returns", "the", "class", "name", "for", "the", "extended", "class" ]
train
https://github.com/kss-php/kss-php/blob/5431bfb3c3708cfedb6a95fc3413181287d1f776/lib/Modifier.php#L176-L186
kss-php/kss-php
lib/Modifier.php
Modifier.getClassName
public function getClassName() { $name = str_replace('.', ' ', $this->name); $name = str_replace(':', ' pseudo-class-', $name); return trim($name); }
php
public function getClassName() { $name = str_replace('.', ' ', $this->name); $name = str_replace(':', ' pseudo-class-', $name); return trim($name); }
[ "public", "function", "getClassName", "(", ")", "{", "$", "name", "=", "str_replace", "(", "'.'", ",", "' '", ",", "$", "this", "->", "name", ")", ";", "$", "name", "=", "str_replace", "(", "':'", ",", "' pseudo-class-'", ",", "$", "name", ")", ";", ...
Returns the class name for the modifier @return string
[ "Returns", "the", "class", "name", "for", "the", "modifier" ]
train
https://github.com/kss-php/kss-php/blob/5431bfb3c3708cfedb6a95fc3413181287d1f776/lib/Modifier.php#L193-L198
kss-php/kss-php
lib/Modifier.php
Modifier.getExampleHtml
public function getExampleHtml($html = null) { if ($html === null) { if ($this->getMarkup() === null) { return ''; } $html = $this->getMarkup(); } if ($this->isExtender()) { $html = str_replace('$modifierClass', '', $html); // Use a positive lookbehind and lookahead to ensure we don't // replace anything more than just the targeted class name // for example an element name that is the same as the extended // class name (e.g. button) $pattern = sprintf('/(?<="| )%s(?="| )/', $this->getExtendedClassName()); $html = preg_replace( $pattern, $this->getClassName(), $html ); } $html = str_replace('$modifierClass', $this->getClassName(), $html); return $html; }
php
public function getExampleHtml($html = null) { if ($html === null) { if ($this->getMarkup() === null) { return ''; } $html = $this->getMarkup(); } if ($this->isExtender()) { $html = str_replace('$modifierClass', '', $html); // Use a positive lookbehind and lookahead to ensure we don't // replace anything more than just the targeted class name // for example an element name that is the same as the extended // class name (e.g. button) $pattern = sprintf('/(?<="| )%s(?="| )/', $this->getExtendedClassName()); $html = preg_replace( $pattern, $this->getClassName(), $html ); } $html = str_replace('$modifierClass', $this->getClassName(), $html); return $html; }
[ "public", "function", "getExampleHtml", "(", "$", "html", "=", "null", ")", "{", "if", "(", "$", "html", "===", "null", ")", "{", "if", "(", "$", "this", "->", "getMarkup", "(", ")", "===", "null", ")", "{", "return", "''", ";", "}", "$", "html",...
Returns a string of specified html with inserted class names in the correct places for modifiers and extenders. @param string $html OPTIONAL @return string $html
[ "Returns", "a", "string", "of", "specified", "html", "with", "inserted", "class", "names", "in", "the", "correct", "places", "for", "modifiers", "and", "extenders", "." ]
train
https://github.com/kss-php/kss-php/blob/5431bfb3c3708cfedb6a95fc3413181287d1f776/lib/Modifier.php#L208-L235
skrz/meta
gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php
NamePartMeta.create
public static function create() { switch (func_num_args()) { case 0: return new NamePart(); case 1: return new NamePart(func_get_arg(0)); case 2: return new NamePart(func_get_arg(0), func_get_arg(1)); case 3: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2)); case 4: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3)); case 5: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4)); case 6: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5)); case 7: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6)); case 8: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6), func_get_arg(7)); default: throw new \InvalidArgumentException('More than 8 arguments supplied, please be reasonable.'); } }
php
public static function create() { switch (func_num_args()) { case 0: return new NamePart(); case 1: return new NamePart(func_get_arg(0)); case 2: return new NamePart(func_get_arg(0), func_get_arg(1)); case 3: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2)); case 4: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3)); case 5: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4)); case 6: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5)); case 7: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6)); case 8: return new NamePart(func_get_arg(0), func_get_arg(1), func_get_arg(2), func_get_arg(3), func_get_arg(4), func_get_arg(5), func_get_arg(6), func_get_arg(7)); default: throw new \InvalidArgumentException('More than 8 arguments supplied, please be reasonable.'); } }
[ "public", "static", "function", "create", "(", ")", "{", "switch", "(", "func_num_args", "(", ")", ")", "{", "case", "0", ":", "return", "new", "NamePart", "(", ")", ";", "case", "1", ":", "return", "new", "NamePart", "(", "func_get_arg", "(", "0", "...
Creates new instance of \Google\Protobuf\UninterpretedOption\NamePart @throws \InvalidArgumentException @return NamePart
[ "Creates", "new", "instance", "of", "\\", "Google", "\\", "Protobuf", "\\", "UninterpretedOption", "\\", "NamePart" ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php#L58-L82
skrz/meta
gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php
NamePartMeta.reset
public static function reset($object) { if (!($object instanceof NamePart)) { throw new \InvalidArgumentException('You have to pass object of class Google\Protobuf\UninterpretedOption\NamePart.'); } $object->namePart = NULL; $object->isExtension = NULL; }
php
public static function reset($object) { if (!($object instanceof NamePart)) { throw new \InvalidArgumentException('You have to pass object of class Google\Protobuf\UninterpretedOption\NamePart.'); } $object->namePart = NULL; $object->isExtension = NULL; }
[ "public", "static", "function", "reset", "(", "$", "object", ")", "{", "if", "(", "!", "(", "$", "object", "instanceof", "NamePart", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'You have to pass object of class Google\\Protobuf\\Uninterpre...
Resets properties of \Google\Protobuf\UninterpretedOption\NamePart to default values @param NamePart $object @throws \InvalidArgumentException @return void
[ "Resets", "properties", "of", "\\", "Google", "\\", "Protobuf", "\\", "UninterpretedOption", "\\", "NamePart", "to", "default", "values" ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php#L95-L102
skrz/meta
gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php
NamePartMeta.hash
public static function hash($object, $algoOrCtx = 'md5', $raw = FALSE) { if (is_string($algoOrCtx)) { $ctx = hash_init($algoOrCtx); } else { $ctx = $algoOrCtx; } if (isset($object->namePart)) { hash_update($ctx, 'namePart'); hash_update($ctx, (string)$object->namePart); } if (isset($object->isExtension)) { hash_update($ctx, 'isExtension'); hash_update($ctx, (string)$object->isExtension); } if (is_string($algoOrCtx)) { return hash_final($ctx, $raw); } else { return null; } }
php
public static function hash($object, $algoOrCtx = 'md5', $raw = FALSE) { if (is_string($algoOrCtx)) { $ctx = hash_init($algoOrCtx); } else { $ctx = $algoOrCtx; } if (isset($object->namePart)) { hash_update($ctx, 'namePart'); hash_update($ctx, (string)$object->namePart); } if (isset($object->isExtension)) { hash_update($ctx, 'isExtension'); hash_update($ctx, (string)$object->isExtension); } if (is_string($algoOrCtx)) { return hash_final($ctx, $raw); } else { return null; } }
[ "public", "static", "function", "hash", "(", "$", "object", ",", "$", "algoOrCtx", "=", "'md5'", ",", "$", "raw", "=", "FALSE", ")", "{", "if", "(", "is_string", "(", "$", "algoOrCtx", ")", ")", "{", "$", "ctx", "=", "hash_init", "(", "$", "algoOrC...
Computes hash of \Google\Protobuf\UninterpretedOption\NamePart @param object $object @param string|resource $algoOrCtx @param bool $raw @return string|void
[ "Computes", "hash", "of", "\\", "Google", "\\", "Protobuf", "\\", "UninterpretedOption", "\\", "NamePart" ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php#L114-L137
skrz/meta
gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php
NamePartMeta.fromProtobuf
public static function fromProtobuf($input, $object = NULL, &$start = 0, $end = NULL) { if ($object === null) { $object = new NamePart(); } if ($end === null) { $end = strlen($input); } while ($start < $end) { $tag = Binary::decodeVarint($input, $start); $wireType = $tag & 0x7; $number = $tag >> 3; switch ($number) { case 1: if ($wireType !== 2) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 2.', $number); } $length = Binary::decodeVarint($input, $start); $expectedStart = $start + $length; if ($expectedStart > $end) { throw new ProtobufException('Not enough data.'); } $object->namePart = substr($input, $start, $length); $start += $length; if ($start !== $expectedStart) { throw new ProtobufException('Unexpected start. Expected ' . $expectedStart . ', got ' . $start . '.', $number); } break; case 2: if ($wireType !== 0) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 0.', $number); } $object->isExtension = (bool)Binary::decodeVarint($input, $start); break; default: switch ($wireType) { case 0: Binary::decodeVarint($input, $start); break; case 1: $start += 8; break; case 2: $start += Binary::decodeVarint($input, $start); break; case 5: $start += 4; break; default: throw new ProtobufException('Unexpected wire type ' . $wireType . '.', $number); } } } return $object; }
php
public static function fromProtobuf($input, $object = NULL, &$start = 0, $end = NULL) { if ($object === null) { $object = new NamePart(); } if ($end === null) { $end = strlen($input); } while ($start < $end) { $tag = Binary::decodeVarint($input, $start); $wireType = $tag & 0x7; $number = $tag >> 3; switch ($number) { case 1: if ($wireType !== 2) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 2.', $number); } $length = Binary::decodeVarint($input, $start); $expectedStart = $start + $length; if ($expectedStart > $end) { throw new ProtobufException('Not enough data.'); } $object->namePart = substr($input, $start, $length); $start += $length; if ($start !== $expectedStart) { throw new ProtobufException('Unexpected start. Expected ' . $expectedStart . ', got ' . $start . '.', $number); } break; case 2: if ($wireType !== 0) { throw new ProtobufException('Unexpected wire type ' . $wireType . ', expected 0.', $number); } $object->isExtension = (bool)Binary::decodeVarint($input, $start); break; default: switch ($wireType) { case 0: Binary::decodeVarint($input, $start); break; case 1: $start += 8; break; case 2: $start += Binary::decodeVarint($input, $start); break; case 5: $start += 4; break; default: throw new ProtobufException('Unexpected wire type ' . $wireType . '.', $number); } } } return $object; }
[ "public", "static", "function", "fromProtobuf", "(", "$", "input", ",", "$", "object", "=", "NULL", ",", "&", "$", "start", "=", "0", ",", "$", "end", "=", "NULL", ")", "{", "if", "(", "$", "object", "===", "null", ")", "{", "$", "object", "=", ...
Creates \Google\Protobuf\UninterpretedOption\NamePart object from serialized Protocol Buffers message. @param string $input @param NamePart $object @param int $start @param int $end @throws \Exception @return NamePart
[ "Creates", "\\", "Google", "\\", "Protobuf", "\\", "UninterpretedOption", "\\", "NamePart", "object", "from", "serialized", "Protocol", "Buffers", "message", "." ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php#L152-L209
skrz/meta
gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php
NamePartMeta.toProtobuf
public static function toProtobuf($object, $filter = NULL) { $output = ''; if (isset($object->namePart) && ($filter === null || isset($filter['namePart']))) { $output .= "\x0a"; $output .= Binary::encodeVarint(strlen($object->namePart)); $output .= $object->namePart; } if (isset($object->isExtension) && ($filter === null || isset($filter['isExtension']))) { $output .= "\x10"; $output .= Binary::encodeVarint((int)$object->isExtension); } return $output; }
php
public static function toProtobuf($object, $filter = NULL) { $output = ''; if (isset($object->namePart) && ($filter === null || isset($filter['namePart']))) { $output .= "\x0a"; $output .= Binary::encodeVarint(strlen($object->namePart)); $output .= $object->namePart; } if (isset($object->isExtension) && ($filter === null || isset($filter['isExtension']))) { $output .= "\x10"; $output .= Binary::encodeVarint((int)$object->isExtension); } return $output; }
[ "public", "static", "function", "toProtobuf", "(", "$", "object", ",", "$", "filter", "=", "NULL", ")", "{", "$", "output", "=", "''", ";", "if", "(", "isset", "(", "$", "object", "->", "namePart", ")", "&&", "(", "$", "filter", "===", "null", "||"...
Serialized \Google\Protobuf\UninterpretedOption\NamePart to Protocol Buffers message. @param NamePart $object @param array $filter @throws \Exception @return string
[ "Serialized", "\\", "Google", "\\", "Protobuf", "\\", "UninterpretedOption", "\\", "NamePart", "to", "Protocol", "Buffers", "message", "." ]
train
https://github.com/skrz/meta/blob/013af6435d3885ab5b2e91fb8ebb051d0f874ab2/gen-src/Google/Protobuf/UninterpretedOption/Meta/NamePartMeta.php#L222-L238
wardrobecms/core-archived
src/Wardrobe/Core/Repositories/DbPostRepository.php
DbPostRepository.active
public function active($per_page) { $per_page = is_numeric($per_page) ? $per_page : 5; return Post::with(array('tags', 'user')) ->where('active', 1) ->where('publish_date', '<=', new DateTime) ->orderBy('publish_date', 'desc') ->paginate($per_page); }
php
public function active($per_page) { $per_page = is_numeric($per_page) ? $per_page : 5; return Post::with(array('tags', 'user')) ->where('active', 1) ->where('publish_date', '<=', new DateTime) ->orderBy('publish_date', 'desc') ->paginate($per_page); }
[ "public", "function", "active", "(", "$", "per_page", ")", "{", "$", "per_page", "=", "is_numeric", "(", "$", "per_page", ")", "?", "$", "per_page", ":", "5", ";", "return", "Post", "::", "with", "(", "array", "(", "'tags'", ",", "'user'", ")", ")", ...
Get all of the active posts. @param int $per_page @return array
[ "Get", "all", "of", "the", "active", "posts", "." ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/Repositories/DbPostRepository.php#L26-L35
wardrobecms/core-archived
src/Wardrobe/Core/Repositories/DbPostRepository.php
DbPostRepository.findBySlug
public function findBySlug($slug) { return Post::with(array('tags', 'user')) ->where('active', 1) ->where('publish_date', '<=', new DateTime) ->where('slug', $slug)->first(); }
php
public function findBySlug($slug) { return Post::with(array('tags', 'user')) ->where('active', 1) ->where('publish_date', '<=', new DateTime) ->where('slug', $slug)->first(); }
[ "public", "function", "findBySlug", "(", "$", "slug", ")", "{", "return", "Post", "::", "with", "(", "array", "(", "'tags'", ",", "'user'", ")", ")", "->", "where", "(", "'active'", ",", "1", ")", "->", "where", "(", "'publish_date'", ",", "'<='", ",...
Get a Post by its slug @param string $slug @return Post
[ "Get", "a", "Post", "by", "its", "slug" ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/Repositories/DbPostRepository.php#L54-L60
wardrobecms/core-archived
src/Wardrobe/Core/Repositories/DbPostRepository.php
DbPostRepository.activeByTag
public function activeByTag($tag, $per_page) { $per_page = is_numeric($per_page) ? $per_page : 5; return Post::with(array('tags', 'user')) ->select('posts.*') ->join('tags', 'posts.id', '=', 'tags.post_id') ->where('tags.tag', '=', $tag) ->orderBy('posts.publish_date', 'desc') ->where('posts.active', 1) ->where('posts.publish_date', '<=', new DateTime) ->distinct() ->paginate($per_page); }
php
public function activeByTag($tag, $per_page) { $per_page = is_numeric($per_page) ? $per_page : 5; return Post::with(array('tags', 'user')) ->select('posts.*') ->join('tags', 'posts.id', '=', 'tags.post_id') ->where('tags.tag', '=', $tag) ->orderBy('posts.publish_date', 'desc') ->where('posts.active', 1) ->where('posts.publish_date', '<=', new DateTime) ->distinct() ->paginate($per_page); }
[ "public", "function", "activeByTag", "(", "$", "tag", ",", "$", "per_page", ")", "{", "$", "per_page", "=", "is_numeric", "(", "$", "per_page", ")", "?", "$", "per_page", ":", "5", ";", "return", "Post", "::", "with", "(", "array", "(", "'tags'", ","...
Get all posts with a tag @param string $tag @param int $per_page @return array
[ "Get", "all", "posts", "with", "a", "tag" ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/Repositories/DbPostRepository.php#L69-L82
wardrobecms/core-archived
src/Wardrobe/Core/Repositories/DbPostRepository.php
DbPostRepository.search
public function search($search, $per_page) { $per_page = is_numeric($per_page) ? $per_page : 5; return Post::with(array('tags', 'user')) ->select('posts.*') ->join('tags', 'posts.id', '=', 'tags.post_id') ->where(function($query) use ($search) { $query->orWhere('title', 'like', '%'.$search.'%') ->orWhere('content', 'like', '%'.$search.'%'); }) ->orderBy('posts.publish_date', 'desc') ->where('posts.active', '=', 1) ->where('posts.publish_date', '<=', new DateTime) ->groupBy('id') ->distinct() ->paginate($per_page); }
php
public function search($search, $per_page) { $per_page = is_numeric($per_page) ? $per_page : 5; return Post::with(array('tags', 'user')) ->select('posts.*') ->join('tags', 'posts.id', '=', 'tags.post_id') ->where(function($query) use ($search) { $query->orWhere('title', 'like', '%'.$search.'%') ->orWhere('content', 'like', '%'.$search.'%'); }) ->orderBy('posts.publish_date', 'desc') ->where('posts.active', '=', 1) ->where('posts.publish_date', '<=', new DateTime) ->groupBy('id') ->distinct() ->paginate($per_page); }
[ "public", "function", "search", "(", "$", "search", ",", "$", "per_page", ")", "{", "$", "per_page", "=", "is_numeric", "(", "$", "per_page", ")", "?", "$", "per_page", ":", "5", ";", "return", "Post", "::", "with", "(", "array", "(", "'tags'", ",", ...
Search all active posts @param string $tag @param int $per_page @return array
[ "Search", "all", "active", "posts" ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/Repositories/DbPostRepository.php#L91-L109
wardrobecms/core-archived
src/Wardrobe/Core/Repositories/DbPostRepository.php
DbPostRepository.facadeSearch
public function facadeSearch(array $params) { $search = isset($params['q']) ? $params['q'] : null; $tag = isset($params['tag']) ? $params['tag'] : null; $limit = isset($params['limit']) ? (int) $params['limit'] : 1; $post = Post::with(array('tags', 'user')) ->select('posts.*') ->join('tags', 'posts.id', '=', 'tags.post_id') ->orderBy('posts.publish_date', 'desc') ->where('posts.active', 1) ->where('posts.publish_date', '<=', new DateTime) ->distinct(); if ($search) { $post->where(function($query) use ($search) { $query->orWhere('title', 'like', '%'.$search.'%') ->orWhere('content', 'like', '%'.$search.'%'); }); } if ($tag) { $post->where('tags.tag', '=', $tag); } return $post->skip(0)->take($limit)->get(); }
php
public function facadeSearch(array $params) { $search = isset($params['q']) ? $params['q'] : null; $tag = isset($params['tag']) ? $params['tag'] : null; $limit = isset($params['limit']) ? (int) $params['limit'] : 1; $post = Post::with(array('tags', 'user')) ->select('posts.*') ->join('tags', 'posts.id', '=', 'tags.post_id') ->orderBy('posts.publish_date', 'desc') ->where('posts.active', 1) ->where('posts.publish_date', '<=', new DateTime) ->distinct(); if ($search) { $post->where(function($query) use ($search) { $query->orWhere('title', 'like', '%'.$search.'%') ->orWhere('content', 'like', '%'.$search.'%'); }); } if ($tag) { $post->where('tags.tag', '=', $tag); } return $post->skip(0)->take($limit)->get(); }
[ "public", "function", "facadeSearch", "(", "array", "$", "params", ")", "{", "$", "search", "=", "isset", "(", "$", "params", "[", "'q'", "]", ")", "?", "$", "params", "[", "'q'", "]", ":", "null", ";", "$", "tag", "=", "isset", "(", "$", "params...
Search from the wardrobe facet @param array $params @return array
[ "Search", "from", "the", "wardrobe", "facet" ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/Repositories/DbPostRepository.php#L117-L146
wardrobecms/core-archived
src/Wardrobe/Core/Repositories/DbPostRepository.php
DbPostRepository.create
public function create($title, $content, $slug, array $tags, $active, $user_id, DateTime $publish_date) { $post = Post::create(compact('title', 'content', 'slug', 'active', 'user_id', 'publish_date')); $post->tags()->delete(); $post->tags()->createMany($this->prepareTags($tags)); return $post; }
php
public function create($title, $content, $slug, array $tags, $active, $user_id, DateTime $publish_date) { $post = Post::create(compact('title', 'content', 'slug', 'active', 'user_id', 'publish_date')); $post->tags()->delete(); $post->tags()->createMany($this->prepareTags($tags)); return $post; }
[ "public", "function", "create", "(", "$", "title", ",", "$", "content", ",", "$", "slug", ",", "array", "$", "tags", ",", "$", "active", ",", "$", "user_id", ",", "DateTime", "$", "publish_date", ")", "{", "$", "post", "=", "Post", "::", "create", ...
Create a new post. @param string $title @param string $content @param string $slug @param array $tags @param bool $active @param int $user_id @param DateTime $publish_date @return Post
[ "Create", "a", "new", "post", "." ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/Repositories/DbPostRepository.php#L160-L169
wardrobecms/core-archived
src/Wardrobe/Core/Repositories/DbPostRepository.php
DbPostRepository.update
public function update($id, $title, $content, $slug, array $tags, $active, $user_id, DateTime $publish_date) { $post = $this->find($id); // Forget the old cache if (Config::get('wardrobe.cache')) { Cache::forget('post-'.$post->id); } $post->fill(compact('title', 'content', 'slug', 'active', 'user_id', 'publish_date'))->save(); $post->tags()->delete(); $post->tags()->createMany($this->prepareTags($tags)); return $post; }
php
public function update($id, $title, $content, $slug, array $tags, $active, $user_id, DateTime $publish_date) { $post = $this->find($id); // Forget the old cache if (Config::get('wardrobe.cache')) { Cache::forget('post-'.$post->id); } $post->fill(compact('title', 'content', 'slug', 'active', 'user_id', 'publish_date'))->save(); $post->tags()->delete(); $post->tags()->createMany($this->prepareTags($tags)); return $post; }
[ "public", "function", "update", "(", "$", "id", ",", "$", "title", ",", "$", "content", ",", "$", "slug", ",", "array", "$", "tags", ",", "$", "active", ",", "$", "user_id", ",", "DateTime", "$", "publish_date", ")", "{", "$", "post", "=", "$", "...
Update a post's title and content. @param int $id @param string $title @param string $content @param string $slug @param array $tags @param string $active @param int $user_id @param \DateTime $publish_date @return Post
[ "Update", "a", "post", "s", "title", "and", "content", "." ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/Repositories/DbPostRepository.php#L185-L202
wardrobecms/core-archived
src/Wardrobe/Core/Repositories/DbPostRepository.php
DbPostRepository.validatePost
protected function validatePost($title, $slug, $id = null) { $rules = array( 'title' => 'required', 'slug' => 'required|unique:posts,slug', ); if ($id) { $rules['slug'] .= ','.$id; } with($validator = Validator::make(compact('title', 'slug'), $rules))->fails(); return $validator->errors(); }
php
protected function validatePost($title, $slug, $id = null) { $rules = array( 'title' => 'required', 'slug' => 'required|unique:posts,slug', ); if ($id) { $rules['slug'] .= ','.$id; } with($validator = Validator::make(compact('title', 'slug'), $rules))->fails(); return $validator->errors(); }
[ "protected", "function", "validatePost", "(", "$", "title", ",", "$", "slug", ",", "$", "id", "=", "null", ")", "{", "$", "rules", "=", "array", "(", "'title'", "=>", "'required'", ",", "'slug'", "=>", "'required|unique:posts,slug'", ",", ")", ";", "if",...
Determine if the given post is valid. @param string $title @param string $slug @param int $id @return \Illuminate\Support\MessageBag
[ "Determine", "if", "the", "given", "post", "is", "valid", "." ]
train
https://github.com/wardrobecms/core-archived/blob/5c0836ea2e6885a428c852dc392073f2a2541c71/src/Wardrobe/Core/Repositories/DbPostRepository.php#L276-L291
marvin255/bxcodegen
src/generator/Orm.php
Orm.generate
public function generate(CollectionInterface $options, ServiceLocatorInterface $locator) { $data = $this->collectDataFromInputForTemplate($options); $this->renderFile($data['model_namespace_with_name'], 'model', $locator, $data); if ($data['create_query']) { $this->renderFile($data['query_namespace_with_name'], 'query', $locator, $data); } }
php
public function generate(CollectionInterface $options, ServiceLocatorInterface $locator) { $data = $this->collectDataFromInputForTemplate($options); $this->renderFile($data['model_namespace_with_name'], 'model', $locator, $data); if ($data['create_query']) { $this->renderFile($data['query_namespace_with_name'], 'query', $locator, $data); } }
[ "public", "function", "generate", "(", "CollectionInterface", "$", "options", ",", "ServiceLocatorInterface", "$", "locator", ")", "{", "$", "data", "=", "$", "this", "->", "collectDataFromInputForTemplate", "(", "$", "options", ")", ";", "$", "this", "->", "r...
{@inheritdoc} @throws \InvalidArgumentException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/generator/Orm.php#L21-L30
marvin255/bxcodegen
src/generator/Orm.php
Orm.renderFile
protected function renderFile($className, $template, ServiceLocatorInterface $locator, array $options) { $templates = dirname(dirname(__DIR__)) . '/templates/orm'; $destinationPath = $locator->get('pathManager')->getAbsolutePathForClass($className); if (!$destinationPath) { throw new InvalidArgumentException( "Can't rout path for {$className} class" ); } $source = new File("{$templates}/{$template}.phptpl"); (new Directory(dirname($destinationPath)))->create(); $destination = new File($destinationPath); if ($destination->isExists()) { throw new InvalidArgumentException( 'File ' . $destination->getPathname() . ' already exists' ); } else { $this->getAndConfigurateCopierFromLocator($locator, $options)->copyFile($source, $destination); } }
php
protected function renderFile($className, $template, ServiceLocatorInterface $locator, array $options) { $templates = dirname(dirname(__DIR__)) . '/templates/orm'; $destinationPath = $locator->get('pathManager')->getAbsolutePathForClass($className); if (!$destinationPath) { throw new InvalidArgumentException( "Can't rout path for {$className} class" ); } $source = new File("{$templates}/{$template}.phptpl"); (new Directory(dirname($destinationPath)))->create(); $destination = new File($destinationPath); if ($destination->isExists()) { throw new InvalidArgumentException( 'File ' . $destination->getPathname() . ' already exists' ); } else { $this->getAndConfigurateCopierFromLocator($locator, $options)->copyFile($source, $destination); } }
[ "protected", "function", "renderFile", "(", "$", "className", ",", "$", "template", ",", "ServiceLocatorInterface", "$", "locator", ",", "array", "$", "options", ")", "{", "$", "templates", "=", "dirname", "(", "dirname", "(", "__DIR__", ")", ")", ".", "'/...
Создает файл из шаблона и копирует его по указанному пути. @param string $className @param string $template @param marvin255\bxcodegen\ServiceLocatorInterface $locator @param array $options @throws \InvalidArgumentException
[ "Создает", "файл", "из", "шаблона", "и", "копирует", "его", "по", "указанному", "пути", "." ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/generator/Orm.php#L42-L64
marvin255/bxcodegen
src/generator/Orm.php
Orm.collectDataFromInputForTemplate
protected function collectDataFromInputForTemplate(CollectionInterface $options) { $table = $options->get('table'); if (!$table) { throw new InvalidArgumentException('table option must be set'); } elseif (!preg_match('/^[a-z0-9_]{3,}$/', $table)) { throw new InvalidArgumentException( 'table option can consist of: latins, digits and _' . ", got: {$table}" ); } $class = $options->get('class'); if (!$class) { throw new InvalidArgumentException('class option must be set'); } elseif (!preg_match('/^[\\\a-zA-Z0-9_]{3,}\\\[a-zA-Z0-9_]+Table$/', $class)) { throw new InvalidArgumentException( 'class option can consist of: latins, digits, _ and \\' . ", ends with 'Table' suffix, got: {$class}" ); } $explodedClass = explode('\\', $class); $className = array_pop($explodedClass); $namespace = implode('\\', $explodedClass); $queryClassName = substr($className, 0, strlen($className) - 5) . 'Query'; return [ 'table' => $table, 'namespace' => $namespace, 'model_namespace_with_name' => $class, 'model_name' => $className, 'query_namespace_with_name' => $namespace . '\\' . $queryClassName, 'query_name' => $queryClassName, 'create_query' => (bool) $options->get('create_query', true), ]; }
php
protected function collectDataFromInputForTemplate(CollectionInterface $options) { $table = $options->get('table'); if (!$table) { throw new InvalidArgumentException('table option must be set'); } elseif (!preg_match('/^[a-z0-9_]{3,}$/', $table)) { throw new InvalidArgumentException( 'table option can consist of: latins, digits and _' . ", got: {$table}" ); } $class = $options->get('class'); if (!$class) { throw new InvalidArgumentException('class option must be set'); } elseif (!preg_match('/^[\\\a-zA-Z0-9_]{3,}\\\[a-zA-Z0-9_]+Table$/', $class)) { throw new InvalidArgumentException( 'class option can consist of: latins, digits, _ and \\' . ", ends with 'Table' suffix, got: {$class}" ); } $explodedClass = explode('\\', $class); $className = array_pop($explodedClass); $namespace = implode('\\', $explodedClass); $queryClassName = substr($className, 0, strlen($className) - 5) . 'Query'; return [ 'table' => $table, 'namespace' => $namespace, 'model_namespace_with_name' => $class, 'model_name' => $className, 'query_namespace_with_name' => $namespace . '\\' . $queryClassName, 'query_name' => $queryClassName, 'create_query' => (bool) $options->get('create_query', true), ]; }
[ "protected", "function", "collectDataFromInputForTemplate", "(", "CollectionInterface", "$", "options", ")", "{", "$", "table", "=", "$", "options", "->", "get", "(", "'table'", ")", ";", "if", "(", "!", "$", "table", ")", "{", "throw", "new", "InvalidArgume...
Собирает массив опций для шаблонов из тех опций, что пришли от пользователя. @param \marvin255\bxcodegen\service\options\CollectionInterface $options @return array @throws \InvalidArgumentException
[ "Собирает", "массив", "опций", "для", "шаблонов", "из", "тех", "опций", "что", "пришли", "от", "пользователя", "." ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/generator/Orm.php#L75-L111
MW-Peachy/Peachy
Includes/Peachy.php
Peachy.newWiki
public static function newWiki( $config_name = null, $pgUsername = null, $password = null, $base_url = 'http://en.wikipedia.org/w/api.php', $classname = 'Wiki' ) { pecho( "Loading Peachy (version " . PEACHYVERSION . ")...\n\n", PECHO_NORMAL ); /*$updater = new AutoUpdate(); $Uptodate = $updater->Checkforupdate(); if( !$Uptodate ) $updater->updatePeachy();*/ if( !is_null( $config_name ) ) { $config_params = self::parse_config( $config_name ); } else { $config_params = array( 'username' => $pgUsername, 'password' => $password, 'baseurl' => $base_url, 'method' => 'legacy' ); } if( is_null( $config_params['baseurl'] ) || !isset( $config_params['baseurl'] ) ) { throw new LoginError( array( "MissingParam", "The baseurl parameter was not set." ) ); } if( !isset( $config_params['username'] ) ) { $config_params['nologin'] = true; } if( !isset( $config_params['password'] ) && isset( $config_params['method'] ) && $config_params['method'] == "legacy" ) { $config_params['nologin'] = true; } list( $version, $extensions ) = self::wikiChecks( $config_params['baseurl'] ); Hooks::runHook( 'StartLogin', array( &$config_params, &$extensions ) ); $w = new $classname( $config_params, $extensions, false, null ); $w->mwversion = $version; return $w; }
php
public static function newWiki( $config_name = null, $pgUsername = null, $password = null, $base_url = 'http://en.wikipedia.org/w/api.php', $classname = 'Wiki' ) { pecho( "Loading Peachy (version " . PEACHYVERSION . ")...\n\n", PECHO_NORMAL ); /*$updater = new AutoUpdate(); $Uptodate = $updater->Checkforupdate(); if( !$Uptodate ) $updater->updatePeachy();*/ if( !is_null( $config_name ) ) { $config_params = self::parse_config( $config_name ); } else { $config_params = array( 'username' => $pgUsername, 'password' => $password, 'baseurl' => $base_url, 'method' => 'legacy' ); } if( is_null( $config_params['baseurl'] ) || !isset( $config_params['baseurl'] ) ) { throw new LoginError( array( "MissingParam", "The baseurl parameter was not set." ) ); } if( !isset( $config_params['username'] ) ) { $config_params['nologin'] = true; } if( !isset( $config_params['password'] ) && isset( $config_params['method'] ) && $config_params['method'] == "legacy" ) { $config_params['nologin'] = true; } list( $version, $extensions ) = self::wikiChecks( $config_params['baseurl'] ); Hooks::runHook( 'StartLogin', array( &$config_params, &$extensions ) ); $w = new $classname( $config_params, $extensions, false, null ); $w->mwversion = $version; return $w; }
[ "public", "static", "function", "newWiki", "(", "$", "config_name", "=", "null", ",", "$", "pgUsername", "=", "null", ",", "$", "password", "=", "null", ",", "$", "base_url", "=", "'http://en.wikipedia.org/w/api.php'", ",", "$", "classname", "=", "'Wiki'", "...
Initializes Peachy, logs in with a either the configuration file or a given username and password @static @access public @param string $config_name Name of the config file stored in the Configs directory, minus the .cfg extension. Default null @param string $pgUsername Username to log in if no config file specified. Default null @param string $password Password to log in with if no config file specified. Default null @param string $base_url URL to api.php if no config file specified. Defaults to English Wikipedia's API. @param string $classname @throws LoginError @return Wiki Instance of the Wiki class, where most functions are stored
[ "Initializes", "Peachy", "logs", "in", "with", "a", "either", "the", "configuration", "file", "or", "a", "given", "username", "and", "password" ]
train
https://github.com/MW-Peachy/Peachy/blob/2cd3f93fd48e06c8a9f9eaaf17c5547947f9613c/Includes/Peachy.php#L23-L61
MW-Peachy/Peachy
Includes/Peachy.php
Peachy.wikiChecks
public static function wikiChecks( $base_url ) { $http = HTTP::getDefaultInstance(); $siteInfo = unserialize( $http->get( $base_url, array( 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'php', 'siprop' => 'extensions|general', ) ) ); if (isset($siteInfo['error']) && $siteInfo['error']['code'] == 'readapidenied') { global $pgHooks; $pgHooks['PostLogin'][] = array( 'Peachy::wikiChecks', $base_url ); return array( MINMW, array() ); } $version = preg_replace('/[^0-9\.]/', '', $siteInfo['query']['general']['generator']); if( version_compare( $version, MINMW ) < 0 ) { throw new DependencyError( "MediaWiki " . MINMW, "http://mediawiki.org" ); } $extensions = array(); foreach ($siteInfo['query']['extensions'] as $ext) { if( isset( $ext['version'] ) ) { $extensions[$ext['name']] = $ext['version']; } else { $extensions[$ext['name']] = ''; } } return array( $version, $extensions ); }
php
public static function wikiChecks( $base_url ) { $http = HTTP::getDefaultInstance(); $siteInfo = unserialize( $http->get( $base_url, array( 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'php', 'siprop' => 'extensions|general', ) ) ); if (isset($siteInfo['error']) && $siteInfo['error']['code'] == 'readapidenied') { global $pgHooks; $pgHooks['PostLogin'][] = array( 'Peachy::wikiChecks', $base_url ); return array( MINMW, array() ); } $version = preg_replace('/[^0-9\.]/', '', $siteInfo['query']['general']['generator']); if( version_compare( $version, MINMW ) < 0 ) { throw new DependencyError( "MediaWiki " . MINMW, "http://mediawiki.org" ); } $extensions = array(); foreach ($siteInfo['query']['extensions'] as $ext) { if( isset( $ext['version'] ) ) { $extensions[$ext['name']] = $ext['version']; } else { $extensions[$ext['name']] = ''; } } return array( $version, $extensions ); }
[ "public", "static", "function", "wikiChecks", "(", "$", "base_url", ")", "{", "$", "http", "=", "HTTP", "::", "getDefaultInstance", "(", ")", ";", "$", "siteInfo", "=", "unserialize", "(", "$", "http", "->", "get", "(", "$", "base_url", ",", "array", "...
Performs various checks and settings Checks if MW version is at least {@link MINMW} @static @access public @param string $base_url URL to api.php @throws DependencyError|string @return array Installed extensions
[ "Performs", "various", "checks", "and", "settings", "Checks", "if", "MW", "version", "is", "at", "least", "{", "@link", "MINMW", "}" ]
train
https://github.com/MW-Peachy/Peachy/blob/2cd3f93fd48e06c8a9f9eaaf17c5547947f9613c/Includes/Peachy.php#L73-L111
MW-Peachy/Peachy
Includes/Peachy.php
Peachy.parse_config
private static function parse_config( $config_name ) { global $pgIP; if( !is_file( $config_name ) ) { if( !is_file( $pgIP . 'Configs/' . $config_name . '.cfg' ) ) { throw new BadEntryError( "BadConfig", "A non-existent configuration file was specified." ); } else { $config_name = $pgIP . 'Configs/' . $config_name . '.cfg'; } } $config_params = parse_ini_file( $config_name ); if( isset( $config_params['useconfig'] ) ) { $config_params = $config_params + self::parse_config( $config_params['useconfig'] ); } return $config_params; }
php
private static function parse_config( $config_name ) { global $pgIP; if( !is_file( $config_name ) ) { if( !is_file( $pgIP . 'Configs/' . $config_name . '.cfg' ) ) { throw new BadEntryError( "BadConfig", "A non-existent configuration file was specified." ); } else { $config_name = $pgIP . 'Configs/' . $config_name . '.cfg'; } } $config_params = parse_ini_file( $config_name ); if( isset( $config_params['useconfig'] ) ) { $config_params = $config_params + self::parse_config( $config_params['useconfig'] ); } return $config_params; }
[ "private", "static", "function", "parse_config", "(", "$", "config_name", ")", "{", "global", "$", "pgIP", ";", "if", "(", "!", "is_file", "(", "$", "config_name", ")", ")", "{", "if", "(", "!", "is_file", "(", "$", "pgIP", ".", "'Configs/'", ".", "$...
Checks for config files, parses them. @access private @static @param string $config_name Name of config file @throws BadEntryError @return array Config params
[ "Checks", "for", "config", "files", "parses", "them", "." ]
train
https://github.com/MW-Peachy/Peachy/blob/2cd3f93fd48e06c8a9f9eaaf17c5547947f9613c/Includes/Peachy.php#L122-L139
MW-Peachy/Peachy
Includes/Peachy.php
Peachy.deprecatedWarn
public static function deprecatedWarn($method, $newFunction, $message = null) { if( is_null( $message ) ) { $message = "Warning: $method is deprecated. Please use $newFunction instead."; } $message = "[$message|YELLOW_BAR]\n\n"; pecho( $message, PECHO_WARN, 'cecho' ); }
php
public static function deprecatedWarn($method, $newFunction, $message = null) { if( is_null( $message ) ) { $message = "Warning: $method is deprecated. Please use $newFunction instead."; } $message = "[$message|YELLOW_BAR]\n\n"; pecho( $message, PECHO_WARN, 'cecho' ); }
[ "public", "static", "function", "deprecatedWarn", "(", "$", "method", ",", "$", "newFunction", ",", "$", "message", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "message", ")", ")", "{", "$", "message", "=", "\"Warning: $method is deprecated. Pleas...
Function that displays an error message when an End-User attempts to use a function no longer included in Peachy @param null|string $method @param null|string $newFunction @param string $message
[ "Function", "that", "displays", "an", "error", "message", "when", "an", "End", "-", "User", "attempts", "to", "use", "a", "function", "no", "longer", "included", "in", "Peachy" ]
train
https://github.com/MW-Peachy/Peachy/blob/2cd3f93fd48e06c8a9f9eaaf17c5547947f9613c/Includes/Peachy.php#L148-L157
MW-Peachy/Peachy
Includes/Peachy.php
Peachy.getSvnInfo
public static function getSvnInfo() { global $pgIP; // http://svnbook.red-bean.com/nightly/en/svn.developer.insidewc.html $entries = $pgIP . '/.svn/entries'; if( !file_exists( $entries ) ) { return false; } $lines = file( $entries ); if( !count( $lines ) ) { return false; } // check if file is xml (subversion release <= 1.3) or not (subversion release = 1.4) if( preg_match( '/^<\?xml/', $lines[0] ) ) { return false; } // Subversion is release 1.4 or above. if( count( $lines ) < 11 ) { return false; } $info = array( 'checkout-rev' => intval( trim( $lines[3] ) ), 'url' => trim( $lines[4] ), 'repo-url' => trim( $lines[5] ), 'directory-rev' => intval( trim( $lines[10] ) ) ); return $info; }
php
public static function getSvnInfo() { global $pgIP; // http://svnbook.red-bean.com/nightly/en/svn.developer.insidewc.html $entries = $pgIP . '/.svn/entries'; if( !file_exists( $entries ) ) { return false; } $lines = file( $entries ); if( !count( $lines ) ) { return false; } // check if file is xml (subversion release <= 1.3) or not (subversion release = 1.4) if( preg_match( '/^<\?xml/', $lines[0] ) ) { return false; } // Subversion is release 1.4 or above. if( count( $lines ) < 11 ) { return false; } $info = array( 'checkout-rev' => intval( trim( $lines[3] ) ), 'url' => trim( $lines[4] ), 'repo-url' => trim( $lines[5] ), 'directory-rev' => intval( trim( $lines[10] ) ) ); return $info; }
[ "public", "static", "function", "getSvnInfo", "(", ")", "{", "global", "$", "pgIP", ";", "// http://svnbook.red-bean.com/nightly/en/svn.developer.insidewc.html", "$", "entries", "=", "$", "pgIP", ".", "'/.svn/entries'", ";", "if", "(", "!", "file_exists", "(", "$", ...
Checks for and returns an SVN repository version. @return array|bool
[ "Checks", "for", "and", "returns", "an", "SVN", "repository", "version", "." ]
train
https://github.com/MW-Peachy/Peachy/blob/2cd3f93fd48e06c8a9f9eaaf17c5547947f9613c/Includes/Peachy.php#L164-L197
joomla-framework/input
src/Cli.php
Cli.serialize
public function serialize() { // Load all of the inputs. $this->loadAllInputs(); // Remove $_ENV and $_SERVER from the inputs. $inputs = $this->inputs; unset($inputs['env'], $inputs['server']); // Serialize the executable, args, options, data, and inputs. return serialize(array($this->executable, $this->args, $this->options, $this->data, $inputs)); }
php
public function serialize() { // Load all of the inputs. $this->loadAllInputs(); // Remove $_ENV and $_SERVER from the inputs. $inputs = $this->inputs; unset($inputs['env'], $inputs['server']); // Serialize the executable, args, options, data, and inputs. return serialize(array($this->executable, $this->args, $this->options, $this->data, $inputs)); }
[ "public", "function", "serialize", "(", ")", "{", "// Load all of the inputs.", "$", "this", "->", "loadAllInputs", "(", ")", ";", "// Remove $_ENV and $_SERVER from the inputs.", "$", "inputs", "=", "$", "this", "->", "inputs", ";", "unset", "(", "$", "inputs", ...
Method to serialize the input. @return string The serialized input. @since 1.0
[ "Method", "to", "serialize", "the", "input", "." ]
train
https://github.com/joomla-framework/input/blob/62c28fa6f5f2d754918d6727ea7e24d4affcff11/src/Cli.php#L71-L82
MW-Peachy/Peachy
Plugins/AbuseFilter.php
AbuseFilter.abuselog
public function abuselog( $filter = null, $user = null, $title = null, $limit = null, $start = null, $end = null, $dir = 'older', $prop = array( 'ids', 'filter', 'user', 'ip', 'title', 'action', 'details', 'result', 'timestamp' ) ) { $tArray = array( 'prop' => $prop, '_code' => 'afl', 'afldir' => $dir, '_limit' => $limit, 'list' => 'abuselog', ); if( !is_null( $filter ) ) $tArray['aflfilter'] = $filter; if( !is_null( $user ) ) $tArray['afluser'] = $user; if( !is_null( $title ) ) $tArray['afltitle'] = $title; if( !is_null( $start ) ) $tArray['aflstart'] = $start; if( !is_null( $end ) ) $tArray['aflend'] = $end; pecho( "Getting abuse log...\n\n", PECHO_NORMAL ); return $this->wiki->listHandler( $tArray ); }
php
public function abuselog( $filter = null, $user = null, $title = null, $limit = null, $start = null, $end = null, $dir = 'older', $prop = array( 'ids', 'filter', 'user', 'ip', 'title', 'action', 'details', 'result', 'timestamp' ) ) { $tArray = array( 'prop' => $prop, '_code' => 'afl', 'afldir' => $dir, '_limit' => $limit, 'list' => 'abuselog', ); if( !is_null( $filter ) ) $tArray['aflfilter'] = $filter; if( !is_null( $user ) ) $tArray['afluser'] = $user; if( !is_null( $title ) ) $tArray['afltitle'] = $title; if( !is_null( $start ) ) $tArray['aflstart'] = $start; if( !is_null( $end ) ) $tArray['aflend'] = $end; pecho( "Getting abuse log...\n\n", PECHO_NORMAL ); return $this->wiki->listHandler( $tArray ); }
[ "public", "function", "abuselog", "(", "$", "filter", "=", "null", ",", "$", "user", "=", "null", ",", "$", "title", "=", "null", ",", "$", "limit", "=", "null", ",", "$", "start", "=", "null", ",", "$", "end", "=", "null", ",", "$", "dir", "="...
Returns the abuse filter log @access public @param int $filter Filter ID. Default null @param string $user Show entries by this user. Default null @param string $title Show entries to this title. Default null @param int $limit Number of entries to retrieve. Defautl null @param string $start Timestamp to start at. Default null @param string $end Timestamp to end at. Default null @param string $dir Direction to list. Default older @param array $prop Properties to retrieve. Default array( 'ids', 'filter', 'user', 'ip', 'title', 'action', 'details', 'result', 'timestamp' ) @return array
[ "Returns", "the", "abuse", "filter", "log" ]
train
https://github.com/MW-Peachy/Peachy/blob/2cd3f93fd48e06c8a9f9eaaf17c5547947f9613c/Plugins/AbuseFilter.php#L60-L81
MW-Peachy/Peachy
Plugins/AbuseFilter.php
AbuseFilter.abusefilters
public function abusefilters( $start = null, $end = null, $dir = 'newer', $enabled = null, $deleted = false, $private = null, $limit = null, $prop = array( 'id', 'description', 'pattern', 'actions', 'hits', 'comments', 'lasteditor', 'lastedittime', 'status', 'private' ) ) { $tArray = array( 'prop' => $prop, '_code' => 'abf', 'abfdir' => $dir, '_limit' => $limit, 'abfshow' => array(), 'list' => 'abusefilters' ); if( !is_null( $enabled ) ) { if( $enabled ) { $tArray['abfshow'][] = 'enabled'; } else { $tArray['abfshow'][] = '!enabled'; } } if( !is_null( $deleted ) ) { if( $deleted ) { $tArray['abfshow'][] = 'deleted'; } else { $tArray['abfshow'][] = '!deleted'; } } if( !is_null( $private ) ) { if( $private ) { $tArray['abfshow'][] = 'private'; } else { $tArray['abfshow'][] = '!private'; } } $tArray['abfshow'] = implode( '|', $tArray['abfshow'] ); if( !is_null( $start ) ) $tArray['abfstartid'] = $start; if( !is_null( $end ) ) $tArray['abfendid'] = $end; pecho( "Getting abuse filter list...\n\n", PECHO_NORMAL ); return $this->wiki->listHandler( $tArray ); }
php
public function abusefilters( $start = null, $end = null, $dir = 'newer', $enabled = null, $deleted = false, $private = null, $limit = null, $prop = array( 'id', 'description', 'pattern', 'actions', 'hits', 'comments', 'lasteditor', 'lastedittime', 'status', 'private' ) ) { $tArray = array( 'prop' => $prop, '_code' => 'abf', 'abfdir' => $dir, '_limit' => $limit, 'abfshow' => array(), 'list' => 'abusefilters' ); if( !is_null( $enabled ) ) { if( $enabled ) { $tArray['abfshow'][] = 'enabled'; } else { $tArray['abfshow'][] = '!enabled'; } } if( !is_null( $deleted ) ) { if( $deleted ) { $tArray['abfshow'][] = 'deleted'; } else { $tArray['abfshow'][] = '!deleted'; } } if( !is_null( $private ) ) { if( $private ) { $tArray['abfshow'][] = 'private'; } else { $tArray['abfshow'][] = '!private'; } } $tArray['abfshow'] = implode( '|', $tArray['abfshow'] ); if( !is_null( $start ) ) $tArray['abfstartid'] = $start; if( !is_null( $end ) ) $tArray['abfendid'] = $end; pecho( "Getting abuse filter list...\n\n", PECHO_NORMAL ); return $this->wiki->listHandler( $tArray ); }
[ "public", "function", "abusefilters", "(", "$", "start", "=", "null", ",", "$", "end", "=", "null", ",", "$", "dir", "=", "'newer'", ",", "$", "enabled", "=", "null", ",", "$", "deleted", "=", "false", ",", "$", "private", "=", "null", ",", "$", ...
Returns a list of all filters @access public @param int $start Filter ID to start at. Default null @param int $end Filter ID to end at. Default null @param string $dir Direction to list. Default newer @param bool $enabled Only list enabled filters. true => only enabled, false => only disabled, null => all @param bool $deleted Only list deleted filters. true => only deleted, false => only non-deleted, null => all @param bool $private Only list private filters. true => only private, false => only non-private, null => all @param int $limit Number of filters to get. Default null @param array $prop Properties to retrieve. Default array( 'id', 'description', 'pattern', 'actions', 'hits', 'comments', 'lasteditor', 'lastedittime', 'status', 'private' ) @return array
[ "Returns", "a", "list", "of", "all", "filters" ]
train
https://github.com/MW-Peachy/Peachy/blob/2cd3f93fd48e06c8a9f9eaaf17c5547947f9613c/Plugins/AbuseFilter.php#L97-L142
baleen/migrations
src/Delta/Collection/Resolver/FirstLastResolver.php
FirstLastResolver.doResolve
protected function doResolve($alias, Collection $collection) { $result = null; switch (strtolower($alias)) { case self::LAST: case self::LATEST: $result = $collection->last(); break; case self::FIRST: case self::EARLIEST: $result = $collection->first(); break; default: } return $result; }
php
protected function doResolve($alias, Collection $collection) { $result = null; switch (strtolower($alias)) { case self::LAST: case self::LATEST: $result = $collection->last(); break; case self::FIRST: case self::EARLIEST: $result = $collection->first(); break; default: } return $result; }
[ "protected", "function", "doResolve", "(", "$", "alias", ",", "Collection", "$", "collection", ")", "{", "$", "result", "=", "null", ";", "switch", "(", "strtolower", "(", "$", "alias", ")", ")", "{", "case", "self", "::", "LAST", ":", "case", "self", ...
Resolves an alias into a Delta. @param string $alias @param Collection $collection @return DeltaInterface|null
[ "Resolves", "an", "alias", "into", "a", "Delta", "." ]
train
https://github.com/baleen/migrations/blob/cfc8c439858cf4f0d4119af9eb67de493da8d95c/src/Delta/Collection/Resolver/FirstLastResolver.php#L44-L59
yeephp/yeephp
Yee/Http/Response.php
Response.status
public function status($status = null) { if (!is_null($status)) { $this->status = (int) $status; } return $this->status; }
php
public function status($status = null) { if (!is_null($status)) { $this->status = (int) $status; } return $this->status; }
[ "public", "function", "status", "(", "$", "status", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "status", ")", ")", "{", "$", "this", "->", "status", "=", "(", "int", ")", "$", "status", ";", "}", "return", "$", "this", "->", "s...
DEPRECATION WARNING! Use `getStatus` or `setStatus` instead. Get and set status @param int|null $status @return int
[ "DEPRECATION", "WARNING!", "Use", "getStatus", "or", "setStatus", "instead", "." ]
train
https://github.com/yeephp/yeephp/blob/6107f60ceaf0811a6550872bd669580ac282cb1f/Yee/Http/Response.php#L160-L167
yeephp/yeephp
Yee/Http/Response.php
Response.header
public function header($name, $value = null) { if (!is_null($value)) { $this->headers->set($name, $value); } return $this->headers->get($name); }
php
public function header($name, $value = null) { if (!is_null($value)) { $this->headers->set($name, $value); } return $this->headers->get($name); }
[ "public", "function", "header", "(", "$", "name", ",", "$", "value", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "value", ")", ")", "{", "$", "this", "->", "headers", "->", "set", "(", "$", "name", ",", "$", "value", ")", ";", ...
DEPRECATION WARNING! Access `headers` property directly. Get and set header @param string $name Header name @param string|null $value Header value @return string Header value
[ "DEPRECATION", "WARNING!", "Access", "headers", "property", "directly", "." ]
train
https://github.com/yeephp/yeephp/blob/6107f60ceaf0811a6550872bd669580ac282cb1f/Yee/Http/Response.php#L177-L184
yeephp/yeephp
Yee/Http/Response.php
Response.body
public function body($body = null) { if (!is_null($body)) { $this->write($body, true); } return $this->body; }
php
public function body($body = null) { if (!is_null($body)) { $this->write($body, true); } return $this->body; }
[ "public", "function", "body", "(", "$", "body", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "body", ")", ")", "{", "$", "this", "->", "write", "(", "$", "body", ",", "true", ")", ";", "}", "return", "$", "this", "->", "body", ...
DEPRECATION WARNING! use `getBody` or `setBody` instead. Get and set body @param string|null $body Content of HTTP response body @return string
[ "DEPRECATION", "WARNING!", "use", "getBody", "or", "setBody", "instead", "." ]
train
https://github.com/yeephp/yeephp/blob/6107f60ceaf0811a6550872bd669580ac282cb1f/Yee/Http/Response.php#L214-L221
yeephp/yeephp
Yee/Http/Response.php
Response.length
public function length($length = null) { if (!is_null($length)) { $this->length = (int) $length; } return $this->length; }
php
public function length($length = null) { if (!is_null($length)) { $this->length = (int) $length; } return $this->length; }
[ "public", "function", "length", "(", "$", "length", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "length", ")", ")", "{", "$", "this", "->", "length", "=", "(", "int", ")", "$", "length", ";", "}", "return", "$", "this", "->", "l...
DEPRECATION WARNING! Use `getLength` or `write` or `body` instead. Get and set length @param int|null $length @return int
[ "DEPRECATION", "WARNING!", "Use", "getLength", "or", "write", "or", "body", "instead", "." ]
train
https://github.com/yeephp/yeephp/blob/6107f60ceaf0811a6550872bd669580ac282cb1f/Yee/Http/Response.php#L253-L260
yeephp/yeephp
Yee/Http/Response.php
Response.finalize
public function finalize() { // Prepare response if (in_array($this->status, array(204, 304))) { $this->headers->remove('Content-Type'); $this->headers->remove('Content-Length'); $this->setBody(''); } return array($this->status, $this->headers, $this->body); }
php
public function finalize() { // Prepare response if (in_array($this->status, array(204, 304))) { $this->headers->remove('Content-Type'); $this->headers->remove('Content-Length'); $this->setBody(''); } return array($this->status, $this->headers, $this->body); }
[ "public", "function", "finalize", "(", ")", "{", "// Prepare response", "if", "(", "in_array", "(", "$", "this", "->", "status", ",", "array", "(", "204", ",", "304", ")", ")", ")", "{", "$", "this", "->", "headers", "->", "remove", "(", "'Content-Type...
Finalize This prepares this response and returns an array of [status, headers, body]. This array is passed to outer middleware if available or directly to the Yee run method. @return array[int status, array headers, string body]
[ "Finalize" ]
train
https://github.com/yeephp/yeephp/blob/6107f60ceaf0811a6550872bd669580ac282cb1f/Yee/Http/Response.php#L271-L281
yeephp/yeephp
Yee/Http/Response.php
Response.getMessageForCode
public static function getMessageForCode($status) { if (isset(self::$messages[$status])) { return self::$messages[$status]; } else { return null; } }
php
public static function getMessageForCode($status) { if (isset(self::$messages[$status])) { return self::$messages[$status]; } else { return null; } }
[ "public", "static", "function", "getMessageForCode", "(", "$", "status", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "messages", "[", "$", "status", "]", ")", ")", "{", "return", "self", "::", "$", "messages", "[", "$", "status", "]", ";", ...
Get message for HTTP status code @param int $status @return string|null
[ "Get", "message", "for", "HTTP", "status", "code" ]
train
https://github.com/yeephp/yeephp/blob/6107f60ceaf0811a6550872bd669580ac282cb1f/Yee/Http/Response.php#L504-L511
nfephp-org/sped-console
src/XsdConverter/Naming/Factory.php
Factory.addAvailableNamingStrategy
public static function addAvailableNamingStrategy($name, $className) { $ref = new \ReflectionClass($className); if (!$ref->isSubclassOf(NamingStrategy::class)) { throw new \InvalidArgumentException($className); } self::$strategies[$name] = $ref->getName(); }
php
public static function addAvailableNamingStrategy($name, $className) { $ref = new \ReflectionClass($className); if (!$ref->isSubclassOf(NamingStrategy::class)) { throw new \InvalidArgumentException($className); } self::$strategies[$name] = $ref->getName(); }
[ "public", "static", "function", "addAvailableNamingStrategy", "(", "$", "name", ",", "$", "className", ")", "{", "$", "ref", "=", "new", "\\", "ReflectionClass", "(", "$", "className", ")", ";", "if", "(", "!", "$", "ref", "->", "isSubclassOf", "(", "Nam...
Adds a new supported driver. @param string $name Driver's name @param string $className Class name of driver @return void @throws \InvalidArgumentException
[ "Adds", "a", "new", "supported", "driver", "." ]
train
https://github.com/nfephp-org/sped-console/blob/eaedaa8065744b2e47d8f7c711ae993ff238126f/src/XsdConverter/Naming/Factory.php#L56-L63
budde377/Part
lib/controller/json/ElementImpl.php
ElementImpl.validValue
protected function validValue(&$val) { if (!is_array($val)) { return $val == null || is_scalar($val) || $val instanceof JsonSerializable; } foreach ($val as $k => $v) { if (!$this->validValue($v)) { $val[$k] = null; } else { $val[$k] = $v; } } return true; }
php
protected function validValue(&$val) { if (!is_array($val)) { return $val == null || is_scalar($val) || $val instanceof JsonSerializable; } foreach ($val as $k => $v) { if (!$this->validValue($v)) { $val[$k] = null; } else { $val[$k] = $v; } } return true; }
[ "protected", "function", "validValue", "(", "&", "$", "val", ")", "{", "if", "(", "!", "is_array", "(", "$", "val", ")", ")", "{", "return", "$", "val", "==", "null", "||", "is_scalar", "(", "$", "val", ")", "||", "$", "val", "instanceof", "JsonSer...
Will check input if it is scalars or elements, or arrays of these @param mixed $val @return bool
[ "Will", "check", "input", "if", "it", "is", "scalars", "or", "elements", "or", "arrays", "of", "these" ]
train
https://github.com/budde377/Part/blob/9ab5ce43dd809f9c563040ae0f7dcb7f56a52c5d/lib/controller/json/ElementImpl.php#L31-L45
xylemical/php-expressions
src/Context.php
Context.getVariable
public function getVariable($name, $default = null) { if (!array_key_exists($name, $this->variables)) { return $default; } return $this->variables[$name]; }
php
public function getVariable($name, $default = null) { if (!array_key_exists($name, $this->variables)) { return $default; } return $this->variables[$name]; }
[ "public", "function", "getVariable", "(", "$", "name", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "variables", ")", ")", "{", "return", "$", "default", ";", "}", "return",...
Get a variable by name, with default support. @param string $name @param mixed $default @return mixed
[ "Get", "a", "variable", "by", "name", "with", "default", "support", "." ]
train
https://github.com/xylemical/php-expressions/blob/4dc7c3a4bb3f335a04cb05b0d41871529cfc9b73/src/Context.php#L42-L48
xylemical/php-expressions
src/Context.php
Context.setVariable
public function setVariable($name, $value) { if (is_null($value)) { unset($this->variables[$name]); } else { $this->variables[$name] = $value; } return $this; }
php
public function setVariable($name, $value) { if (is_null($value)) { unset($this->variables[$name]); } else { $this->variables[$name] = $value; } return $this; }
[ "public", "function", "setVariable", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "is_null", "(", "$", "value", ")", ")", "{", "unset", "(", "$", "this", "->", "variables", "[", "$", "name", "]", ")", ";", "}", "else", "{", "$", "t...
Set a variable value by name. @param string $name @param mixed $value @return static
[ "Set", "a", "variable", "value", "by", "name", "." ]
train
https://github.com/xylemical/php-expressions/blob/4dc7c3a4bb3f335a04cb05b0d41871529cfc9b73/src/Context.php#L68-L77
marvin255/bxcodegen
src/service/filesystem/Directory.php
Directory.delete
public function delete() { $return = false; if ($this->isExists()) { foreach ($this as $child) { $child->delete(); } if (!rmdir($this->getPathname())) { throw new RuntimeException("Can't delete folder: " . $this->getPathname()); } $return = true; } return $return; }
php
public function delete() { $return = false; if ($this->isExists()) { foreach ($this as $child) { $child->delete(); } if (!rmdir($this->getPathname())) { throw new RuntimeException("Can't delete folder: " . $this->getPathname()); } $return = true; } return $return; }
[ "public", "function", "delete", "(", ")", "{", "$", "return", "=", "false", ";", "if", "(", "$", "this", "->", "isExists", "(", ")", ")", "{", "foreach", "(", "$", "this", "as", "$", "child", ")", "{", "$", "child", "->", "delete", "(", ")", ";...
{@inheritdoc} @throws \RuntimeException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/service/filesystem/Directory.php#L103-L117
marvin255/bxcodegen
src/service/filesystem/Directory.php
Directory.create
public function create() { $return = false; if (!$this->isExists()) { if (mkdir($this->getPathname(), 0777, true)) { $return = true; } else { throw new RuntimeException("Can't create " . $this->getPathname() . ' folder'); } } return $return; }
php
public function create() { $return = false; if (!$this->isExists()) { if (mkdir($this->getPathname(), 0777, true)) { $return = true; } else { throw new RuntimeException("Can't create " . $this->getPathname() . ' folder'); } } return $return; }
[ "public", "function", "create", "(", ")", "{", "$", "return", "=", "false", ";", "if", "(", "!", "$", "this", "->", "isExists", "(", ")", ")", "{", "if", "(", "mkdir", "(", "$", "this", "->", "getPathname", "(", ")", ",", "0777", ",", "true", "...
{@inheritdoc} @throws \RuntimeException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/service/filesystem/Directory.php#L124-L136
marvin255/bxcodegen
src/service/filesystem/Directory.php
Directory.createChildDirectory
public function createChildDirectory($name) { if ( strpos($name, '\\') !== false || strpos($name, '/') !== false || strpos($name, '..') !== false ) { throw new InvalidArgumentException("Wrong folder name {$name}"); } return new self($this->absolutePath . '/' . $name, $this->fileClass); }
php
public function createChildDirectory($name) { if ( strpos($name, '\\') !== false || strpos($name, '/') !== false || strpos($name, '..') !== false ) { throw new InvalidArgumentException("Wrong folder name {$name}"); } return new self($this->absolutePath . '/' . $name, $this->fileClass); }
[ "public", "function", "createChildDirectory", "(", "$", "name", ")", "{", "if", "(", "strpos", "(", "$", "name", ",", "'\\\\'", ")", "!==", "false", "||", "strpos", "(", "$", "name", ",", "'/'", ")", "!==", "false", "||", "strpos", "(", "$", "name", ...
{@inheritdoc} @throws \InvalidArgumentException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/service/filesystem/Directory.php#L143-L154
marvin255/bxcodegen
src/service/filesystem/Directory.php
Directory.createChildFile
public function createChildFile($name) { if ( strpos($name, '\\') !== false || strpos($name, '/') !== false || strpos($name, '..') !== false ) { throw new InvalidArgumentException("Wrong file name {$name}"); } $class = $this->fileClass; return new $class($this->absolutePath . '/' . $name); }
php
public function createChildFile($name) { if ( strpos($name, '\\') !== false || strpos($name, '/') !== false || strpos($name, '..') !== false ) { throw new InvalidArgumentException("Wrong file name {$name}"); } $class = $this->fileClass; return new $class($this->absolutePath . '/' . $name); }
[ "public", "function", "createChildFile", "(", "$", "name", ")", "{", "if", "(", "strpos", "(", "$", "name", ",", "'\\\\'", ")", "!==", "false", "||", "strpos", "(", "$", "name", ",", "'/'", ")", "!==", "false", "||", "strpos", "(", "$", "name", ","...
{@inheritdoc} @throws \InvalidArgumentException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/service/filesystem/Directory.php#L161-L174
marvin255/bxcodegen
src/service/filesystem/Directory.php
Directory.getIterator
protected function getIterator() { if ($this->iterator === null && $this->isExists()) { $dirIterator = new DirectoryIterator($this->getPathname()); $this->iterator = new CallbackFilterIterator($dirIterator, function ($current, $key, $iterator) { return !$iterator->isDot(); }); } return $this->iterator; }
php
protected function getIterator() { if ($this->iterator === null && $this->isExists()) { $dirIterator = new DirectoryIterator($this->getPathname()); $this->iterator = new CallbackFilterIterator($dirIterator, function ($current, $key, $iterator) { return !$iterator->isDot(); }); } return $this->iterator; }
[ "protected", "function", "getIterator", "(", ")", "{", "if", "(", "$", "this", "->", "iterator", "===", "null", "&&", "$", "this", "->", "isExists", "(", ")", ")", "{", "$", "dirIterator", "=", "new", "DirectoryIterator", "(", "$", "this", "->", "getPa...
Возвращает внутренний объект итератора для перебора содержимого данной папки. @return \DirectoryIterator
[ "Возвращает", "внутренний", "объект", "итератора", "для", "перебора", "содержимого", "данной", "папки", "." ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/service/filesystem/Directory.php#L229-L239
matrozov/yii2-couchbase
src/Command.php
Command.getRawSql
public function getRawSql() { if (empty($this->params)) { return $this->_sql; } $params = []; foreach ($this->params as $name => $value) { if (is_string($name) && strncmp(':', $name, 1)) { $name = '$' . $name; } if (is_string($value)) { $params[$name] = $this->db->quoteValue($value); } elseif (is_bool($value)) { $params[$name] = ($value ? 'TRUE' : 'FALSE'); } elseif ($value === null) { $params[$name] = 'NULL'; } elseif (!is_object($value) && !is_resource($value)) { $params[$name] = $value; } } $this->prepare(); if (!isset($params[1])) { return strtr($this->_sql, $params); } $sql = ''; foreach (explode('$', $this->_sql) as $i => $part) { $sql .= (isset($params[$i]) ? $params[$i] : '') . $part; } return $sql; }
php
public function getRawSql() { if (empty($this->params)) { return $this->_sql; } $params = []; foreach ($this->params as $name => $value) { if (is_string($name) && strncmp(':', $name, 1)) { $name = '$' . $name; } if (is_string($value)) { $params[$name] = $this->db->quoteValue($value); } elseif (is_bool($value)) { $params[$name] = ($value ? 'TRUE' : 'FALSE'); } elseif ($value === null) { $params[$name] = 'NULL'; } elseif (!is_object($value) && !is_resource($value)) { $params[$name] = $value; } } $this->prepare(); if (!isset($params[1])) { return strtr($this->_sql, $params); } $sql = ''; foreach (explode('$', $this->_sql) as $i => $part) { $sql .= (isset($params[$i]) ? $params[$i] : '') . $part; } return $sql; }
[ "public", "function", "getRawSql", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "params", ")", ")", "{", "return", "$", "this", "->", "_sql", ";", "}", "$", "params", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "params", ...
Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]]. Note that the return value of this method should mainly be used for logging purpose. It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders. @return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]]. @throws Exception @throws \yii\base\InvalidConfigException
[ "Returns", "the", "raw", "SQL", "by", "inserting", "parameter", "values", "into", "the", "corresponding", "placeholders", "in", "[[", "sql", "]]", ".", "Note", "that", "the", "return", "value", "of", "this", "method", "should", "mainly", "be", "used", "for",...
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L90-L130
matrozov/yii2-couchbase
src/Command.php
Command.bindParam
public function bindParam($name, &$value) { $name = ltrim($name, '$'); $this->params[$name] =& $value; return $this; }
php
public function bindParam($name, &$value) { $name = ltrim($name, '$'); $this->params[$name] =& $value; return $this; }
[ "public", "function", "bindParam", "(", "$", "name", ",", "&", "$", "value", ")", "{", "$", "name", "=", "ltrim", "(", "$", "name", ",", "'$'", ")", ";", "$", "this", "->", "params", "[", "$", "name", "]", "=", "&", "$", "value", ";", "return",...
Binds a parameter to the SQL statement to be executed. @param string|int $name parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form `:name`. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter. @param mixed $value the PHP variable to bind to the SQL statement parameter (passed by reference) @return $this the current command being executed @see http://www.php.net/manual/en/function.PDOStatement-bindParam.php
[ "Binds", "a", "parameter", "to", "the", "SQL", "statement", "to", "be", "executed", "." ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L185-L192
matrozov/yii2-couchbase
src/Command.php
Command.bindValue
public function bindValue($name, $value) { $name = ltrim($name, '$'); $this->params[$name] = $value; return $this; }
php
public function bindValue($name, $value) { $name = ltrim($name, '$'); $this->params[$name] = $value; return $this; }
[ "public", "function", "bindValue", "(", "$", "name", ",", "$", "value", ")", "{", "$", "name", "=", "ltrim", "(", "$", "name", ",", "'$'", ")", ";", "$", "this", "->", "params", "[", "$", "name", "]", "=", "$", "value", ";", "return", "$", "thi...
Binds a value to a parameter. @param string|int $name Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form `:name`. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter. @param mixed $value The value to bind to the parameter @return $this the current command being executed @see http://www.php.net/manual/en/function.PDOStatement-bindValue.php
[ "Binds", "a", "value", "to", "a", "parameter", "." ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L204-L211
matrozov/yii2-couchbase
src/Command.php
Command.bindValues
public function bindValues($values) { if (empty($values)) { return $this; } foreach ($values as $name => $value) { $this->bindValue($name, $value); } return $this; }
php
public function bindValues($values) { if (empty($values)) { return $this; } foreach ($values as $name => $value) { $this->bindValue($name, $value); } return $this; }
[ "public", "function", "bindValues", "(", "$", "values", ")", "{", "if", "(", "empty", "(", "$", "values", ")", ")", "{", "return", "$", "this", ";", "}", "foreach", "(", "$", "values", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "this",...
Binds a list of values to the corresponding parameters. This is similar to [[bindValue()]] except that it binds multiple values at a time. Note that the SQL data type of each value is determined by its PHP type. @param array $values the values to be bound. This must be given in terms of an associative array with array keys being the parameter names, and array values the corresponding parameter values, e.g. `[':name' => 'John', ':age' => 25]`. By default, the PDO type of each value is determined by its PHP type. You may explicitly specify the PDO type by using an array: `[value, type]`, e.g. `[':name' => 'John', ':profile' => [$profile, \PDO::PARAM_LOB]]`. @return $this the current command being executed
[ "Binds", "a", "list", "of", "values", "to", "the", "corresponding", "parameters", ".", "This", "is", "similar", "to", "[[", "bindValue", "()", "]]", "except", "that", "it", "binds", "multiple", "values", "at", "a", "time", ".", "Note", "that", "the", "SQ...
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L224-L235
matrozov/yii2-couchbase
src/Command.php
Command.insert
public function insert($bucketName, $data) { $sql = $this->db->getQueryBuilder()->insert($bucketName, $data); return $this->setSql($sql)->setBucketName($bucketName); }
php
public function insert($bucketName, $data) { $sql = $this->db->getQueryBuilder()->insert($bucketName, $data); return $this->setSql($sql)->setBucketName($bucketName); }
[ "public", "function", "insert", "(", "$", "bucketName", ",", "$", "data", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "insert", "(", "$", "bucketName", ",", "$", "data", ")", ";", "return", "$", "thi...
Creates an INSERT command. For example, ```php $connection->createCommand()->insert('user', [ 'name' => 'Sam', 'age' => 30, ])->execute(); ``` or ``` $id = $connection->createCommand()->insert('user', [ 'name' => 'Sam', 'age' => 30, ])->queryScalar(); ``` The method will properly escape the column names, and bind the values to be inserted. Note that the created command is not executed until [[execute()]] or [[queryScalar()]] is called. @param string $bucketName the bucket that new rows will be inserted into. @param array $data the column data (name => value) to be inserted into the bucket or instance. @return $this the command object itself
[ "Creates", "an", "INSERT", "command", ".", "For", "example" ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L266-L271
matrozov/yii2-couchbase
src/Command.php
Command.batchInsert
public function batchInsert($bucketName, $rows) { $sql = $this->db->getQueryBuilder()->batchInsert($bucketName, $rows); return $this->setSql($sql)->setBucketName($bucketName); }
php
public function batchInsert($bucketName, $rows) { $sql = $this->db->getQueryBuilder()->batchInsert($bucketName, $rows); return $this->setSql($sql)->setBucketName($bucketName); }
[ "public", "function", "batchInsert", "(", "$", "bucketName", ",", "$", "rows", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "batchInsert", "(", "$", "bucketName", ",", "$", "rows", ")", ";", "return", "...
Creates a batch INSERT command. For example, ```php $connection->createCommand()->batchInsert('user', ['name', 'age'], [ ['Tom', 30], ['Jane', 20], ['Linda', 25], ])->execute(); ``` The method will properly escape the column names, and quote the values to be inserted. Note that the values in each row must match the corresponding column names. Also note that the created command is not executed until [[execute()]] is called. @param string $bucketName the bucket that new rows will be inserted into. @param array $rows the rows to be batch inserted into the bucket. @return $this the command object itself
[ "Creates", "a", "batch", "INSERT", "command", ".", "For", "example" ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L296-L301
matrozov/yii2-couchbase
src/Command.php
Command.update
public function update($bucketName, $columns, $condition, $params = []) { $sql = $this->db->getQueryBuilder()->update($bucketName, $columns, $condition, $params); return $this->setSql($sql)->setBucketName($bucketName)->bindValues($params); }
php
public function update($bucketName, $columns, $condition, $params = []) { $sql = $this->db->getQueryBuilder()->update($bucketName, $columns, $condition, $params); return $this->setSql($sql)->setBucketName($bucketName)->bindValues($params); }
[ "public", "function", "update", "(", "$", "bucketName", ",", "$", "columns", ",", "$", "condition", ",", "$", "params", "=", "[", "]", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "update", "(", "$", ...
Creates an UPDATE command. For example, ```php $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute(); ``` The method will properly escape the column names and bind the values to be updated. Note that the created command is not executed until [[execute()]] is called. @param string $bucketName the bucket to be updated. @param array $columns the column data (name => value) to be updated. @param string|array $condition the condition that will be put in the WHERE part. Please refer to [[Query::where()]] on how to specify condition. @param array $params the parameters to be bound to the command @return $this the command object itself @throws Exception
[ "Creates", "an", "UPDATE", "command", ".", "For", "example" ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L324-L329
matrozov/yii2-couchbase
src/Command.php
Command.upsert
public function upsert($bucketName, $id, $data) { $sql = $this->db->getQueryBuilder()->upsert($bucketName, $id, $data); return $this->setSql($sql)->setBucketName($bucketName); }
php
public function upsert($bucketName, $id, $data) { $sql = $this->db->getQueryBuilder()->upsert($bucketName, $id, $data); return $this->setSql($sql)->setBucketName($bucketName); }
[ "public", "function", "upsert", "(", "$", "bucketName", ",", "$", "id", ",", "$", "data", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "upsert", "(", "$", "bucketName", ",", "$", "id", ",", "$", "da...
Creates an UPSERT command. For example, ```php $connection->createCommand()->upsert('user', 'my-id', ['status' => 1])->execute(); ``` The method will properly escape the column names and bind the values to be updated. Note that the created command is not executed until [[execute()]] is called. @param string $bucketName the bucket to be updated. @param string $id the document id. @param array $data the column data (name => value) to be inserted into the bucket or instance. @return $this the command object itself
[ "Creates", "an", "UPSERT", "command", ".", "For", "example" ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L349-L354
matrozov/yii2-couchbase
src/Command.php
Command.delete
public function delete($bucketName, $condition = '', $params = []) { $sql = $this->db->getQueryBuilder()->delete($bucketName, $condition, $params); return $this->setSql($sql)->setBucketName($bucketName)->bindValues($params); }
php
public function delete($bucketName, $condition = '', $params = []) { $sql = $this->db->getQueryBuilder()->delete($bucketName, $condition, $params); return $this->setSql($sql)->setBucketName($bucketName)->bindValues($params); }
[ "public", "function", "delete", "(", "$", "bucketName", ",", "$", "condition", "=", "''", ",", "$", "params", "=", "[", "]", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "delete", "(", "$", "bucketNam...
Creates a DELETE command. For example, ```php $connection->createCommand()->delete('user', 'status = 0')->execute(); ``` The method will properly escape the bucket and column names. Note that the created command is not executed until [[execute()]] is called. @param string $bucketName the bucket where the data will be deleted from. @param string|array $condition the condition that will be put in the WHERE part. Please refer to [[Query::where()]] on how to specify condition. @param array $params the parameters to be bound to the command @return $this the command object itself @throws Exception
[ "Creates", "a", "DELETE", "command", ".", "For", "example" ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L376-L381
matrozov/yii2-couchbase
src/Command.php
Command.buildIndex
public function buildIndex($bucketName, $indexNames) { $sql = $this->db->getQueryBuilder()->buildIndex($bucketName, $indexNames); return $this->setSql($sql)->setBucketName($bucketName); }
php
public function buildIndex($bucketName, $indexNames) { $sql = $this->db->getQueryBuilder()->buildIndex($bucketName, $indexNames); return $this->setSql($sql)->setBucketName($bucketName); }
[ "public", "function", "buildIndex", "(", "$", "bucketName", ",", "$", "indexNames", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "buildIndex", "(", "$", "bucketName", ",", "$", "indexNames", ")", ";", "re...
Create a SQL command for build index. @param string $bucketName @param string|string[] $indexNames names of index @return $this the command object itself
[ "Create", "a", "SQL", "command", "for", "build", "index", "." ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L418-L423
matrozov/yii2-couchbase
src/Command.php
Command.createPrimaryIndex
public function createPrimaryIndex($bucketName, $indexName = null, $options = []) { $sql = $this->db->getQueryBuilder()->createPrimaryIndex($bucketName, $indexName, $options); return $this->setSql($sql)->setBucketName($bucketName); }
php
public function createPrimaryIndex($bucketName, $indexName = null, $options = []) { $sql = $this->db->getQueryBuilder()->createPrimaryIndex($bucketName, $indexName, $options); return $this->setSql($sql)->setBucketName($bucketName); }
[ "public", "function", "createPrimaryIndex", "(", "$", "bucketName", ",", "$", "indexName", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "createPrimaryIndex",...
Create a SQL command for creating a new primary index. @param string $bucketName @param string|null $indexName name of primary index (optional) @param array $options @return $this the command object itself
[ "Create", "a", "SQL", "command", "for", "creating", "a", "new", "primary", "index", "." ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L434-L439
matrozov/yii2-couchbase
src/Command.php
Command.dropPrimaryIndex
public function dropPrimaryIndex($bucketName) { $sql = $this->db->getQueryBuilder()->dropPrimaryIndex($bucketName); return $this->setSql($sql)->setBucketName($bucketName); }
php
public function dropPrimaryIndex($bucketName) { $sql = $this->db->getQueryBuilder()->dropPrimaryIndex($bucketName); return $this->setSql($sql)->setBucketName($bucketName); }
[ "public", "function", "dropPrimaryIndex", "(", "$", "bucketName", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "dropPrimaryIndex", "(", "$", "bucketName", ")", ";", "return", "$", "this", "->", "setSql", "(...
Create a SQL command for dropping an unnamed primary index. @param string $bucketName @return $this the command object itself
[ "Create", "a", "SQL", "command", "for", "dropping", "an", "unnamed", "primary", "index", "." ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L448-L453
matrozov/yii2-couchbase
src/Command.php
Command.createIndex
public function createIndex($bucketName, $indexName, $columns, $condition = null, &$params = [], $options = []) { $sql = $this->db->getQueryBuilder()->createIndex($bucketName, $indexName, $columns, $condition, $params, $options); return $this->setSql($sql)->setBucketName($bucketName); }
php
public function createIndex($bucketName, $indexName, $columns, $condition = null, &$params = [], $options = []) { $sql = $this->db->getQueryBuilder()->createIndex($bucketName, $indexName, $columns, $condition, $params, $options); return $this->setSql($sql)->setBucketName($bucketName); }
[ "public", "function", "createIndex", "(", "$", "bucketName", ",", "$", "indexName", ",", "$", "columns", ",", "$", "condition", "=", "null", ",", "&", "$", "params", "=", "[", "]", ",", "$", "options", "=", "[", "]", ")", "{", "$", "sql", "=", "$...
Creates a SQL command for creating a new index. @param string $bucketName @param string $indexName @param array $columns @param array|null $condition @param array $params @param array $options @return $this the command object itself @throws Exception
[ "Creates", "a", "SQL", "command", "for", "creating", "a", "new", "index", "." ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L468-L473
matrozov/yii2-couchbase
src/Command.php
Command.dropIndex
public function dropIndex($bucketName, $indexName) { $sql = $this->db->getQueryBuilder()->dropIndex($bucketName, $indexName); return $this->setSql($sql)->setBucketName($bucketName); }
php
public function dropIndex($bucketName, $indexName) { $sql = $this->db->getQueryBuilder()->dropIndex($bucketName, $indexName); return $this->setSql($sql)->setBucketName($bucketName); }
[ "public", "function", "dropIndex", "(", "$", "bucketName", ",", "$", "indexName", ")", "{", "$", "sql", "=", "$", "this", "->", "db", "->", "getQueryBuilder", "(", ")", "->", "dropIndex", "(", "$", "bucketName", ",", "$", "indexName", ")", ";", "return...
Creates a SQL command for dropping an index. @param string $bucketName @param string $indexName @return $this the command object itself
[ "Creates", "a", "SQL", "command", "for", "dropping", "an", "index", "." ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L483-L488
matrozov/yii2-couchbase
src/Command.php
Command.execute
public function execute() { list($profile, $rawSql) = $this->logQuery(__METHOD__); $this->prepare(); $result = true; try { $profile and Yii::beginProfile($rawSql, __METHOD__); $res = $this->db->getBucket($this->_bucketName)->bucket->query($this->n1ql, true); if ($res->status === 'success') { if (isset($res->metrics['mutationCount'])) { $result = $res->metrics['mutationCount']; } } else { $result = false; } $profile and Yii::endProfile($rawSql, __METHOD__); } catch (\Exception $e) { $profile and Yii::endProfile($rawSql, __METHOD__); //throw $this->db->getSchema()->convertException($e, $rawSql ?: $this->getRawSql()); //TODO: FixIt throw new Exception($e->getMessage() . PHP_EOL . ' Sql query: ' . $rawSql, (int)$e->getCode(), $e); } return $result; }
php
public function execute() { list($profile, $rawSql) = $this->logQuery(__METHOD__); $this->prepare(); $result = true; try { $profile and Yii::beginProfile($rawSql, __METHOD__); $res = $this->db->getBucket($this->_bucketName)->bucket->query($this->n1ql, true); if ($res->status === 'success') { if (isset($res->metrics['mutationCount'])) { $result = $res->metrics['mutationCount']; } } else { $result = false; } $profile and Yii::endProfile($rawSql, __METHOD__); } catch (\Exception $e) { $profile and Yii::endProfile($rawSql, __METHOD__); //throw $this->db->getSchema()->convertException($e, $rawSql ?: $this->getRawSql()); //TODO: FixIt throw new Exception($e->getMessage() . PHP_EOL . ' Sql query: ' . $rawSql, (int)$e->getCode(), $e); } return $result; }
[ "public", "function", "execute", "(", ")", "{", "list", "(", "$", "profile", ",", "$", "rawSql", ")", "=", "$", "this", "->", "logQuery", "(", "__METHOD__", ")", ";", "$", "this", "->", "prepare", "(", ")", ";", "$", "result", "=", "true", ";", "...
Executes the SQL statement. This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs. No result set will be returned. @return int|bool number of rows affected by the execution. @throws Exception @throws \yii\base\InvalidConfigException
[ "Executes", "the", "SQL", "statement", ".", "This", "method", "should", "only", "be", "used", "for", "executing", "non", "-", "query", "SQL", "statement", "such", "as", "INSERT", "DELETE", "UPDATE", "SQLs", ".", "No", "result", "set", "will", "be", "return...
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L498-L530
matrozov/yii2-couchbase
src/Command.php
Command.queryInternal
protected function queryInternal($method = null, $columnName = null) { list($profile, $rawSql) = $this->logQuery('yii\db\Command::query'); $this->prepare(); $result = false; try { $profile and Yii::beginProfile($rawSql, 'yii\db\Command::query'); $res = $this->db->getBucket($this->_bucketName)->bucket->query($this->n1ql, true); if ($res->status == 'success') { switch ($method) { case self::FETCH_ALL: { $result = $res->rows; } break; case self::FETCH_ONE: { if (!empty($res->rows)) { $result = $res->rows[0]; } } break; case self::FETCH_SCALAR: { if (!empty($res->rows)) { if ($columnName === null) { $columnName = array_keys($res->rows[0])[0]; } $result = $res->rows[0][$columnName]; } } break; case self::FETCH_COLUMN: { if (!empty($res->rows)) { if ($columnName === null) { $columnName = array_keys($res->rows[0])[0]; } $result = []; foreach ($res->rows as $row) { $result[] = $row[$columnName]; } } } break; default: { $result = $res; } } } $profile and Yii::endProfile($rawSql, 'yii\db\Command::query'); } catch (\Exception $e) { $profile and Yii::endProfile($rawSql, 'yii\db\Command::query'); //throw $this->db->getSchema()->convertException($e, $rawSql ?: $this->getRawSql()); //TODO: FixIt throw new Exception($e->getMessage() . PHP_EOL . ' Sql query: ' . $rawSql, (int)$e->getCode(), $e); } return $result; }
php
protected function queryInternal($method = null, $columnName = null) { list($profile, $rawSql) = $this->logQuery('yii\db\Command::query'); $this->prepare(); $result = false; try { $profile and Yii::beginProfile($rawSql, 'yii\db\Command::query'); $res = $this->db->getBucket($this->_bucketName)->bucket->query($this->n1ql, true); if ($res->status == 'success') { switch ($method) { case self::FETCH_ALL: { $result = $res->rows; } break; case self::FETCH_ONE: { if (!empty($res->rows)) { $result = $res->rows[0]; } } break; case self::FETCH_SCALAR: { if (!empty($res->rows)) { if ($columnName === null) { $columnName = array_keys($res->rows[0])[0]; } $result = $res->rows[0][$columnName]; } } break; case self::FETCH_COLUMN: { if (!empty($res->rows)) { if ($columnName === null) { $columnName = array_keys($res->rows[0])[0]; } $result = []; foreach ($res->rows as $row) { $result[] = $row[$columnName]; } } } break; default: { $result = $res; } } } $profile and Yii::endProfile($rawSql, 'yii\db\Command::query'); } catch (\Exception $e) { $profile and Yii::endProfile($rawSql, 'yii\db\Command::query'); //throw $this->db->getSchema()->convertException($e, $rawSql ?: $this->getRawSql()); //TODO: FixIt throw new Exception($e->getMessage() . PHP_EOL . ' Sql query: ' . $rawSql, (int)$e->getCode(), $e); } return $result; }
[ "protected", "function", "queryInternal", "(", "$", "method", "=", "null", ",", "$", "columnName", "=", "null", ")", "{", "list", "(", "$", "profile", ",", "$", "rawSql", ")", "=", "$", "this", "->", "logQuery", "(", "'yii\\db\\Command::query'", ")", ";"...
Performs the actual DB query of a SQL statement. @param string $method method of PDOStatement to be called @param null|string $columnName @return mixed the method execution result @throws Exception @throws \yii\base\InvalidConfigException
[ "Performs", "the", "actual", "DB", "query", "of", "a", "SQL", "statement", "." ]
train
https://github.com/matrozov/yii2-couchbase/blob/07c2e9d18cb90f873c0d88dcacf6bb532e9d648c/src/Command.php#L615-L676
MW-Peachy/Peachy
Includes/Hooks.php
Hooks.runHook
public static function runHook( $hook_name, $args = array() ) { global $pgHooks; if( !isset( $pgHooks[$hook_name] ) ) return null; if( !is_array( $pgHooks[$hook_name] ) ) { throw new HookError( "Hook assignment for event `$hook_name` is not an array. Syntax is " . '$pgHooks[\'hookname\'][] = "hook_function";' ); } $method = null; foreach( $pgHooks[$hook_name] as $function ){ if( is_array( $function ) ) { if( count( $function ) < 2 ) { throw new HookError( "Not enough parameters in array specified for `$hook_name` hook" ); } elseif( is_object( $function[0] ) ) { $object = $function[0]; $method = $function[1]; if( count( $function ) > 2 ) { $data = $function[2]; } } elseif( is_string( $function[0] ) ) { $method = $function[0]; if( count( $function ) > 1 ) { $data = $function[1]; } } } elseif( is_string( $function ) ) { $method = $function; } if( isset( $data ) ) { $args = array_merge( array( $data ), $args ); } if( isset( $object ) ) { $fncarr = array( $object, $method ); } elseif( is_string( $method ) && in_string( "::", $method ) ) { $fncarr = explode( "::", $method ); } else { $fncarr = $method; } //is_callable( $fncarr ); //Apparently this is a bug. Thanks, MW! if( !is_callable( $fncarr ) ) { throw new BadEntryError( "MissingFunction", "Hook function $fncarr was not defined" ); } $hookRet = call_user_func_array( $fncarr, $args ); if( !is_null( $hookRet ) ) return $hookRet; } }
php
public static function runHook( $hook_name, $args = array() ) { global $pgHooks; if( !isset( $pgHooks[$hook_name] ) ) return null; if( !is_array( $pgHooks[$hook_name] ) ) { throw new HookError( "Hook assignment for event `$hook_name` is not an array. Syntax is " . '$pgHooks[\'hookname\'][] = "hook_function";' ); } $method = null; foreach( $pgHooks[$hook_name] as $function ){ if( is_array( $function ) ) { if( count( $function ) < 2 ) { throw new HookError( "Not enough parameters in array specified for `$hook_name` hook" ); } elseif( is_object( $function[0] ) ) { $object = $function[0]; $method = $function[1]; if( count( $function ) > 2 ) { $data = $function[2]; } } elseif( is_string( $function[0] ) ) { $method = $function[0]; if( count( $function ) > 1 ) { $data = $function[1]; } } } elseif( is_string( $function ) ) { $method = $function; } if( isset( $data ) ) { $args = array_merge( array( $data ), $args ); } if( isset( $object ) ) { $fncarr = array( $object, $method ); } elseif( is_string( $method ) && in_string( "::", $method ) ) { $fncarr = explode( "::", $method ); } else { $fncarr = $method; } //is_callable( $fncarr ); //Apparently this is a bug. Thanks, MW! if( !is_callable( $fncarr ) ) { throw new BadEntryError( "MissingFunction", "Hook function $fncarr was not defined" ); } $hookRet = call_user_func_array( $fncarr, $args ); if( !is_null( $hookRet ) ) return $hookRet; } }
[ "public", "static", "function", "runHook", "(", "$", "hook_name", ",", "$", "args", "=", "array", "(", ")", ")", "{", "global", "$", "pgHooks", ";", "if", "(", "!", "isset", "(", "$", "pgHooks", "[", "$", "hook_name", "]", ")", ")", "return", "null...
Search for hook functions and run them if defined @param string $hook_name Name of hook to search for @param array $args Arguments to pass to the hook function @throws HookError @throws BadEntryError @return mixed Output of hook function
[ "Search", "for", "hook", "functions", "and", "run", "them", "if", "defined" ]
train
https://github.com/MW-Peachy/Peachy/blob/2cd3f93fd48e06c8a9f9eaaf17c5547947f9613c/Includes/Hooks.php#L42-L97
ladamalina/yii2-smsc
src/Smsc.php
Smsc.send_sms
public function send_sms($phones, $message, $translit = 0, $time = 0, $id = 0, $format = 0, $sender = false, $query = "") { static $formats = array(1 => "flash=1", "push=1", "hlr=1", "bin=1", "bin=2", "ping=1"); $m = $this->_smsc_send_cmd("send", "cost=3&phones=".urlencode($phones)."&mes=".urlencode($message). "&translit=$translit&id=$id".($format > 0 ? "&".$formats[$format] : ""). ($sender === false ? "" : "&sender=".urlencode($sender)). ($time ? "&time=".urlencode($time) : "").($query ? "&$query" : "")); // (id, cnt, cost, balance) или (id, -error) if ($this->debug) { if ($m[1] > 0) echo "Сообщение отправлено успешно. ID: $m[0], всего SMS: $m[1], стоимость: $m[2], баланс: $m[3].\n"; else echo "Ошибка №", -$m[1], $m[0] ? ", ID: ".$m[0] : "", "\n"; } return $m; }
php
public function send_sms($phones, $message, $translit = 0, $time = 0, $id = 0, $format = 0, $sender = false, $query = "") { static $formats = array(1 => "flash=1", "push=1", "hlr=1", "bin=1", "bin=2", "ping=1"); $m = $this->_smsc_send_cmd("send", "cost=3&phones=".urlencode($phones)."&mes=".urlencode($message). "&translit=$translit&id=$id".($format > 0 ? "&".$formats[$format] : ""). ($sender === false ? "" : "&sender=".urlencode($sender)). ($time ? "&time=".urlencode($time) : "").($query ? "&$query" : "")); // (id, cnt, cost, balance) или (id, -error) if ($this->debug) { if ($m[1] > 0) echo "Сообщение отправлено успешно. ID: $m[0], всего SMS: $m[1], стоимость: $m[2], баланс: $m[3].\n"; else echo "Ошибка №", -$m[1], $m[0] ? ", ID: ".$m[0] : "", "\n"; } return $m; }
[ "public", "function", "send_sms", "(", "$", "phones", ",", "$", "message", ",", "$", "translit", "=", "0", ",", "$", "time", "=", "0", ",", "$", "id", "=", "0", ",", "$", "format", "=", "0", ",", "$", "sender", "=", "false", ",", "$", "query", ...
/* Функция отправки SMS обязательные параметры: $phones - список телефонов через запятую или точку с запятой $message - отправляемое сообщение необязательные параметры: $translit - переводить или нет в транслит (1,2 или 0) $time - необходимое время доставки в виде строки (DDMMYYhhmm, h1-h2, 0ts, +m) $id - идентификатор сообщения. Представляет собой 32-битное число в диапазоне от 1 до 2147483647. $format - формат сообщения (0 - обычное sms, 1 - flash-sms, 2 - wap-push, 3 - hlr, 4 - bin, 5 - bin-hex, 6 - ping-sms) $sender - имя отправителя (Sender ID). Для отключения Sender ID по умолчанию необходимо в качестве имени передать пустую строку или точку. $query - строка дополнительных параметров, добавляемая в URL-запрос ("valid=01:00&maxsms=3&tz=2") возвращает массив (<id>, <количество sms>, <стоимость>, <баланс>) в случае успешной отправки либо массив (<id>, -<код ошибки>) в случае ошибки
[ "/", "*", "Функция", "отправки", "SMS" ]
train
https://github.com/ladamalina/yii2-smsc/blob/f61d07a13e8fe5c611075e5db60d21f73159d502/src/Smsc.php#L66-L85
ladamalina/yii2-smsc
src/Smsc.php
Smsc.send_sms_mail
public function send_sms_mail($phones, $message, $translit = 0, $time = 0, $id = 0, $format = 0, $sender = "") { return mail("send@send.smsc.ru", "", $this->login.":".$this->password.":$id:$time:$translit,$format,$sender:$phones:$message", "From: ".$this->from."\nContent-Type: text/plain; charset=".$this->charset."\n"); }
php
public function send_sms_mail($phones, $message, $translit = 0, $time = 0, $id = 0, $format = 0, $sender = "") { return mail("send@send.smsc.ru", "", $this->login.":".$this->password.":$id:$time:$translit,$format,$sender:$phones:$message", "From: ".$this->from."\nContent-Type: text/plain; charset=".$this->charset."\n"); }
[ "public", "function", "send_sms_mail", "(", "$", "phones", ",", "$", "message", ",", "$", "translit", "=", "0", ",", "$", "time", "=", "0", ",", "$", "id", "=", "0", ",", "$", "format", "=", "0", ",", "$", "sender", "=", "\"\"", ")", "{", "retu...
SMTP версия функции отправки SMS
[ "SMTP", "версия", "функции", "отправки", "SMS" ]
train
https://github.com/ladamalina/yii2-smsc/blob/f61d07a13e8fe5c611075e5db60d21f73159d502/src/Smsc.php#L90-L93
ladamalina/yii2-smsc
src/Smsc.php
Smsc.get_sms_cost
public function get_sms_cost($phones, $message, $translit = 0, $format = 0, $sender = false, $query = "") { static $formats = array(1 => "flash=1", "push=1", "hlr=1", "bin=1", "bin=2", "ping=1"); $m = $this->_smsc_send_cmd("send", "cost=1&phones=".urlencode($phones)."&mes=".urlencode($message). ($sender === false ? "" : "&sender=".urlencode($sender)). "&translit=$translit".($format > 0 ? "&".$formats[$format] : "").($query ? "&$query" : "")); // (cost, cnt) или (0, -error) if ($this->debug) { if ($m[1] > 0) echo "Стоимость рассылки: $m[0]. Всего SMS: $m[1]\n"; else echo "Ошибка №", -$m[1], "\n"; } return $m; }
php
public function get_sms_cost($phones, $message, $translit = 0, $format = 0, $sender = false, $query = "") { static $formats = array(1 => "flash=1", "push=1", "hlr=1", "bin=1", "bin=2", "ping=1"); $m = $this->_smsc_send_cmd("send", "cost=1&phones=".urlencode($phones)."&mes=".urlencode($message). ($sender === false ? "" : "&sender=".urlencode($sender)). "&translit=$translit".($format > 0 ? "&".$formats[$format] : "").($query ? "&$query" : "")); // (cost, cnt) или (0, -error) if ($this->debug) { if ($m[1] > 0) echo "Стоимость рассылки: $m[0]. Всего SMS: $m[1]\n"; else echo "Ошибка №", -$m[1], "\n"; } return $m; }
[ "public", "function", "get_sms_cost", "(", "$", "phones", ",", "$", "message", ",", "$", "translit", "=", "0", ",", "$", "format", "=", "0", ",", "$", "sender", "=", "false", ",", "$", "query", "=", "\"\"", ")", "{", "static", "$", "formats", "=", ...
/* Функция получения стоимости SMS обязательные параметры: $phones - список телефонов через запятую или точку с запятой $message - отправляемое сообщение необязательные параметры: $translit - переводить или нет в транслит (1,2 или 0) $format - формат сообщения (0 - обычное sms, 1 - flash-sms, 2 - wap-push, 3 - hlr, 4 - bin, 5 - bin-hex, 6 - ping-sms) $sender - имя отправителя (Sender ID) $query - строка дополнительных параметров, добавляемая в URL-запрос ("list=79999999999:Ваш пароль: 123\n78888888888:Ваш пароль: 456") возвращает массив (<стоимость>, <количество sms>) либо массив (0, -<код ошибки>) в случае ошибки
[ "/", "*", "Функция", "получения", "стоимости", "SMS" ]
train
https://github.com/ladamalina/yii2-smsc/blob/f61d07a13e8fe5c611075e5db60d21f73159d502/src/Smsc.php#L114-L132
ladamalina/yii2-smsc
src/Smsc.php
Smsc.get_status
public function get_status($id, $phone, $all = 0) { $m = $this->_smsc_send_cmd("status", "phone=".urlencode($phone)."&id=".$id."&all=".(int)$all); // (status, time, err, ...) или (0, -error) if ($this->debug) { if ($m[1] != "" && $m[1] >= 0) echo "Статус SMS = $m[0]", $m[1] ? ", время изменения статуса - ".date("d.m.Y H:i:s", $m[1]) : "", "\n"; else echo "Ошибка №", -$m[1], "\n"; } if ($all && count($m) > 9 && (!isset($m[14]) || $m[14] != "HLR")) // ',' в сообщении $m = explode(",", implode(",", $m), 9); return $m; }
php
public function get_status($id, $phone, $all = 0) { $m = $this->_smsc_send_cmd("status", "phone=".urlencode($phone)."&id=".$id."&all=".(int)$all); // (status, time, err, ...) или (0, -error) if ($this->debug) { if ($m[1] != "" && $m[1] >= 0) echo "Статус SMS = $m[0]", $m[1] ? ", время изменения статуса - ".date("d.m.Y H:i:s", $m[1]) : "", "\n"; else echo "Ошибка №", -$m[1], "\n"; } if ($all && count($m) > 9 && (!isset($m[14]) || $m[14] != "HLR")) // ',' в сообщении $m = explode(",", implode(",", $m), 9); return $m; }
[ "public", "function", "get_status", "(", "$", "id", ",", "$", "phone", ",", "$", "all", "=", "0", ")", "{", "$", "m", "=", "$", "this", "->", "_smsc_send_cmd", "(", "\"status\"", ",", "\"phone=\"", ".", "urlencode", "(", "$", "phone", ")", ".", "\"...
/* Функция проверки статуса отправленного SMS или HLR-запроса $id - ID cообщения $phone - номер телефона $all - вернуть все данные отправленного SMS, включая текст сообщения (0 или 1) возвращает массив: для SMS-сообщения: (<статус>, <время изменения>, <код ошибки доставки>) для HLR-запроса: (<статус>, <время изменения>, <код ошибки sms>, <код IMSI SIM-карты>, <номер сервис-центра>, <код страны регистрации>, <код оператора>, <название страны регистрации>, <название оператора>, <название роуминговой страны>, <название роумингового оператора>) При $all = 1 дополнительно возвращаются элементы в конце массива: (<время отправки>, <номер телефона>, <стоимость>, <sender id>, <название статуса>, <текст сообщения>) либо массив (0, -<код ошибки>) в случае ошибки
[ "/", "*", "Функция", "проверки", "статуса", "отправленного", "SMS", "или", "HLR", "-", "запроса" ]
train
https://github.com/ladamalina/yii2-smsc/blob/f61d07a13e8fe5c611075e5db60d21f73159d502/src/Smsc.php#L157-L174
ladamalina/yii2-smsc
src/Smsc.php
Smsc.get_balance
public function get_balance() { $m = $this->_smsc_send_cmd("balance"); // (balance) или (0, -error) if ($this->debug) { if (!isset($m[1])) echo "Сумма на счете: ", $m[0], "\n"; else echo "Ошибка №", -$m[1], "\n"; } return isset($m[1]) ? false : $m[0]; }
php
public function get_balance() { $m = $this->_smsc_send_cmd("balance"); // (balance) или (0, -error) if ($this->debug) { if (!isset($m[1])) echo "Сумма на счете: ", $m[0], "\n"; else echo "Ошибка №", -$m[1], "\n"; } return isset($m[1]) ? false : $m[0]; }
[ "public", "function", "get_balance", "(", ")", "{", "$", "m", "=", "$", "this", "->", "_smsc_send_cmd", "(", "\"balance\"", ")", ";", "// (balance) или (0, -error)", "if", "(", "$", "this", "->", "debug", ")", "{", "if", "(", "!", "isset", "(", "$", "m...
/* Функция получения баланса без параметров возвращает баланс в виде строки или false в случае ошибки
[ "/", "*", "Функция", "получения", "баланса" ]
train
https://github.com/ladamalina/yii2-smsc/blob/f61d07a13e8fe5c611075e5db60d21f73159d502/src/Smsc.php#L186-L198
ladamalina/yii2-smsc
src/Smsc.php
Smsc._smsc_send_cmd
private function _smsc_send_cmd($cmd, $arg = "") { $url = ($this->https ? "https" : "http")."://smsc.ru/sys/$cmd.php?login=".urlencode($this->login)."&psw=".urlencode($this->password)."&fmt=1&charset=".$this->charset."&".$arg; $i = 0; do { if ($i) { sleep(2); if ($i == 2) $url = str_replace('://smsc.ru/', '://www2.smsc.ru/', $url); } $ret = $this->_smsc_read_url($url); } while ($ret == "" && ++$i < 3); if ($ret == "") { if ($this->debug) echo "Ошибка чтения адреса: $url\n"; $ret = ","; // фиктивный ответ } return explode(",", $ret); }
php
private function _smsc_send_cmd($cmd, $arg = "") { $url = ($this->https ? "https" : "http")."://smsc.ru/sys/$cmd.php?login=".urlencode($this->login)."&psw=".urlencode($this->password)."&fmt=1&charset=".$this->charset."&".$arg; $i = 0; do { if ($i) { sleep(2); if ($i == 2) $url = str_replace('://smsc.ru/', '://www2.smsc.ru/', $url); } $ret = $this->_smsc_read_url($url); } while ($ret == "" && ++$i < 3); if ($ret == "") { if ($this->debug) echo "Ошибка чтения адреса: $url\n"; $ret = ","; // фиктивный ответ } return explode(",", $ret); }
[ "private", "function", "_smsc_send_cmd", "(", "$", "cmd", ",", "$", "arg", "=", "\"\"", ")", "{", "$", "url", "=", "(", "$", "this", "->", "https", "?", "\"https\"", ":", "\"http\"", ")", ".", "\"://smsc.ru/sys/$cmd.php?login=\"", ".", "urlencode", "(", ...
Функция вызова запроса. Формирует URL и делает 3 попытки чтения
[ "Функция", "вызова", "запроса", ".", "Формирует", "URL", "и", "делает", "3", "попытки", "чтения" ]
train
https://github.com/ladamalina/yii2-smsc/blob/f61d07a13e8fe5c611075e5db60d21f73159d502/src/Smsc.php#L207-L232
ladamalina/yii2-smsc
src/Smsc.php
Smsc._smsc_read_url
private function _smsc_read_url($url) { $ret = ""; $post = $this->post || strlen($url) > 2000; if (function_exists("curl_init")) { static $c = 0; // keepalive if (!$c) { $c = curl_init(); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($c, CURLOPT_TIMEOUT, 30); curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0); } if ($post) { list($url, $post) = explode("?", $url, 2); curl_setopt($c, CURLOPT_POST, true); curl_setopt($c, CURLOPT_POSTFIELDS, $post); } curl_setopt($c, CURLOPT_URL, $url); $ret = curl_exec($c); } elseif (!$this->https && function_exists("fsockopen")) { $m = parse_url($url); if (!$fp = fsockopen($m["host"], 80, $errno, $errstr, 10)) $fp = fsockopen("78.129.199.124", 80, $errno, $errstr, 10); if ($fp) { fwrite($fp, ($post ? "POST $m[path]" : "GET $m[path]?$m[query]")." HTTP/1.1\r\nHost: smsc.ru\r\nUser-Agent: PHP".($post ? "\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($m['query']) : "")."\r\nConnection: Close\r\n\r\n".($post ? $m['query'] : "")); while (!feof($fp)) $ret .= fgets($fp, 1024); list(, $ret) = explode("\r\n\r\n", $ret, 2); fclose($fp); } } else $ret = file_get_contents($url); return $ret; }
php
private function _smsc_read_url($url) { $ret = ""; $post = $this->post || strlen($url) > 2000; if (function_exists("curl_init")) { static $c = 0; // keepalive if (!$c) { $c = curl_init(); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($c, CURLOPT_TIMEOUT, 30); curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0); } if ($post) { list($url, $post) = explode("?", $url, 2); curl_setopt($c, CURLOPT_POST, true); curl_setopt($c, CURLOPT_POSTFIELDS, $post); } curl_setopt($c, CURLOPT_URL, $url); $ret = curl_exec($c); } elseif (!$this->https && function_exists("fsockopen")) { $m = parse_url($url); if (!$fp = fsockopen($m["host"], 80, $errno, $errstr, 10)) $fp = fsockopen("78.129.199.124", 80, $errno, $errstr, 10); if ($fp) { fwrite($fp, ($post ? "POST $m[path]" : "GET $m[path]?$m[query]")." HTTP/1.1\r\nHost: smsc.ru\r\nUser-Agent: PHP".($post ? "\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($m['query']) : "")."\r\nConnection: Close\r\n\r\n".($post ? $m['query'] : "")); while (!feof($fp)) $ret .= fgets($fp, 1024); list(, $ret) = explode("\r\n\r\n", $ret, 2); fclose($fp); } } else $ret = file_get_contents($url); return $ret; }
[ "private", "function", "_smsc_read_url", "(", "$", "url", ")", "{", "$", "ret", "=", "\"\"", ";", "$", "post", "=", "$", "this", "->", "post", "||", "strlen", "(", "$", "url", ")", ">", "2000", ";", "if", "(", "function_exists", "(", "\"curl_init\"",...
/* Функция чтения URL. Для работы должно быть доступно: curl или fsockopen (только http) или включена опция allow_url_fopen для file_get_contents
[ "/", "*", "Функция", "чтения", "URL", ".", "Для", "работы", "должно", "быть", "доступно", ":", "curl", "или", "fsockopen", "(", "только", "http", ")", "или", "включена", "опция", "allow_url_fopen", "для", "file_get_contents" ]
train
https://github.com/ladamalina/yii2-smsc/blob/f61d07a13e8fe5c611075e5db60d21f73159d502/src/Smsc.php#L240-L288
kaliop-uk/kueueingbundle
Service/MessageConsumer.php
MessageConsumer.setAssumedContentType
protected function setAssumedContentType($type) { if (!in_array($type, $this->acceptedContentTypes)) { throw new \InvalidArgumentException("Content type '$type' is not accepted, so it can not be assumed"); } $this->assumedContentType = $type; }
php
protected function setAssumedContentType($type) { if (!in_array($type, $this->acceptedContentTypes)) { throw new \InvalidArgumentException("Content type '$type' is not accepted, so it can not be assumed"); } $this->assumedContentType = $type; }
[ "protected", "function", "setAssumedContentType", "(", "$", "type", ")", "{", "if", "(", "!", "in_array", "(", "$", "type", ",", "$", "this", "->", "acceptedContentTypes", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Content type '$...
Sets the content type which is assumed when the incoming message does not specify any @see decodeMessageBody for those which can be natively decoded @param string $type @throws \InvalidArgumentException
[ "Sets", "the", "content", "type", "which", "is", "assumed", "when", "the", "incoming", "message", "does", "not", "specify", "any", "@see", "decodeMessageBody", "for", "those", "which", "can", "be", "natively", "decoded" ]
train
https://github.com/kaliop-uk/kueueingbundle/blob/6a4f9b01ef1f5b8e5cdfad78f7c82b35f1007987/Service/MessageConsumer.php#L96-L102
kaliop-uk/kueueingbundle
Service/MessageConsumer.php
MessageConsumer.getDriverForMessage
protected function getDriverForMessage($message) { $this->loadRegisteredDrivers(); foreach ($this->drivers as $driver) { if ($driver->acceptMessage($message)) return $driver; } throw new \Exception('No driver found to decode message of type: ' . get_class($message)); }
php
protected function getDriverForMessage($message) { $this->loadRegisteredDrivers(); foreach ($this->drivers as $driver) { if ($driver->acceptMessage($message)) return $driver; } throw new \Exception('No driver found to decode message of type: ' . get_class($message)); }
[ "protected", "function", "getDriverForMessage", "(", "$", "message", ")", "{", "$", "this", "->", "loadRegisteredDrivers", "(", ")", ";", "foreach", "(", "$", "this", "->", "drivers", "as", "$", "driver", ")", "{", "if", "(", "$", "driver", "->", "accept...
Finds a driver appropriate to decode the message @param mixed $message @return DriverInterface @throws \Exception
[ "Finds", "a", "driver", "appropriate", "to", "decode", "the", "message" ]
train
https://github.com/kaliop-uk/kueueingbundle/blob/6a4f9b01ef1f5b8e5cdfad78f7c82b35f1007987/Service/MessageConsumer.php#L134-L143
kaliop-uk/kueueingbundle
Service/MessageConsumer.php
MessageConsumer.decodeAndConsume
protected function decodeAndConsume(MessageInterface $msg) { if ($this->currentMessage != null) { throw new \Exception("Inception. In this reality plane MessageConsumer is not allowed to consume multiple messages in parallel"); } // save the message, in case child class needs it for whacky stuff $this->currentMessage = $msg; $body = null; try { $body = $this->decodeMessageBody($msg); // while at it, emit a message, and allow listeners to prevent further execution if ($this->dispatcher) { $event = new MessageReceivedEvent($msg, $body, $this); if ($this->dispatcher->dispatch(EventsList::MESSAGE_RECEIVED, $event)->isPropagationStopped()) { return; } } $result = $this->consume($body); // q: should we one more try-catch block here, to prevent firing MESSAGE_CONSUMPTION_FAILED if in fact the // consumption went fine? if ($this->dispatcher) { $event = new MessageConsumedEvent($msg, $body, $this, $result); $this->dispatcher->dispatch(EventsList::MESSAGE_CONSUMED, $event); } } catch (\Exception $e) { // we keep on working, but log an error and emit a message if ($this->logger) { $this->logger->error('Unexpected exception trying to decode and consume message: ' . $e->getMessage()); } if ($this->dispatcher) { $event = new MessageConsumptionFailedEvent($msg, $body, $this, $e); $this->dispatcher->dispatch(EventsList::MESSAGE_CONSUMPTION_FAILED, $event); } } $this->currentMessage = null; }
php
protected function decodeAndConsume(MessageInterface $msg) { if ($this->currentMessage != null) { throw new \Exception("Inception. In this reality plane MessageConsumer is not allowed to consume multiple messages in parallel"); } // save the message, in case child class needs it for whacky stuff $this->currentMessage = $msg; $body = null; try { $body = $this->decodeMessageBody($msg); // while at it, emit a message, and allow listeners to prevent further execution if ($this->dispatcher) { $event = new MessageReceivedEvent($msg, $body, $this); if ($this->dispatcher->dispatch(EventsList::MESSAGE_RECEIVED, $event)->isPropagationStopped()) { return; } } $result = $this->consume($body); // q: should we one more try-catch block here, to prevent firing MESSAGE_CONSUMPTION_FAILED if in fact the // consumption went fine? if ($this->dispatcher) { $event = new MessageConsumedEvent($msg, $body, $this, $result); $this->dispatcher->dispatch(EventsList::MESSAGE_CONSUMED, $event); } } catch (\Exception $e) { // we keep on working, but log an error and emit a message if ($this->logger) { $this->logger->error('Unexpected exception trying to decode and consume message: ' . $e->getMessage()); } if ($this->dispatcher) { $event = new MessageConsumptionFailedEvent($msg, $body, $this, $e); $this->dispatcher->dispatch(EventsList::MESSAGE_CONSUMPTION_FAILED, $event); } } $this->currentMessage = null; }
[ "protected", "function", "decodeAndConsume", "(", "MessageInterface", "$", "msg", ")", "{", "if", "(", "$", "this", "->", "currentMessage", "!=", "null", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Inception. In this reality plane MessageConsumer is not allow...
Decodes the message body, dispatches the reception event, and calls consume() @param MessageInterface $msg @throws \Exception only known case: if event listeners try to abuse the API @todo validate message format
[ "Decodes", "the", "message", "body", "dispatches", "the", "reception", "event", "and", "calls", "consume", "()", "@param", "MessageInterface", "$msg", "@throws", "\\", "Exception", "only", "known", "case", ":", "if", "event", "listeners", "try", "to", "abuse", ...
train
https://github.com/kaliop-uk/kueueingbundle/blob/6a4f9b01ef1f5b8e5cdfad78f7c82b35f1007987/Service/MessageConsumer.php#L161-L206
kaliop-uk/kueueingbundle
Service/MessageConsumer.php
MessageConsumer.decodeMessageBody
protected function decodeMessageBody(MessageInterface $msg) { // do we accept this type? (nb: this is an optional property) $type = $msg->getContentType(); if ($type == '' && $this->assumedContentType != '') { $type = $this->assumedContentType; } if ($type == '' || !in_array($type, $this->acceptedContentTypes)) { throw new \RuntimeException("Can not decode message with content type: '$type'"); } // then decode it switch ($type) { case 'application/json': $data = json_decode($msg->getBody(), true); if ($error = json_last_error()) { throw new \UnexpectedValueException("Error decoding json payload: " . $error); } return $data; case 'application/x-httpd-php-source': /// @todo should we wrap this in try/catch, ob_start and set_error_handler, or just make sure it is never used? return eval ('return ' . $msg->body . ';'); case 'vnd.php.serialized': return unserialize($msg->body); case 'text/plain': case 'application/octet-stream': return $msg->body; default: throw new \UnexpectedValueException("Serialization format unsupported: " . $type); } }
php
protected function decodeMessageBody(MessageInterface $msg) { // do we accept this type? (nb: this is an optional property) $type = $msg->getContentType(); if ($type == '' && $this->assumedContentType != '') { $type = $this->assumedContentType; } if ($type == '' || !in_array($type, $this->acceptedContentTypes)) { throw new \RuntimeException("Can not decode message with content type: '$type'"); } // then decode it switch ($type) { case 'application/json': $data = json_decode($msg->getBody(), true); if ($error = json_last_error()) { throw new \UnexpectedValueException("Error decoding json payload: " . $error); } return $data; case 'application/x-httpd-php-source': /// @todo should we wrap this in try/catch, ob_start and set_error_handler, or just make sure it is never used? return eval ('return ' . $msg->body . ';'); case 'vnd.php.serialized': return unserialize($msg->body); case 'text/plain': case 'application/octet-stream': return $msg->body; default: throw new \UnexpectedValueException("Serialization format unsupported: " . $type); } }
[ "protected", "function", "decodeMessageBody", "(", "MessageInterface", "$", "msg", ")", "{", "// do we accept this type? (nb: this is an optional property)", "$", "type", "=", "$", "msg", "->", "getContentType", "(", ")", ";", "if", "(", "$", "type", "==", "''", "...
Works on the basis of the assumed and accepted content types @param MessageInterface $msg @return mixed @throws \RuntimeException @throws \UnexpectedValueException
[ "Works", "on", "the", "basis", "of", "the", "assumed", "and", "accepted", "content", "types" ]
train
https://github.com/kaliop-uk/kueueingbundle/blob/6a4f9b01ef1f5b8e5cdfad78f7c82b35f1007987/Service/MessageConsumer.php#L216-L246
mrTimofey/laravel-simple-tokens
src/SimpleProvider.php
SimpleProvider.forget
public function forget(string $token): void { $this->cache->forget($this->getCacheKey($token)); }
php
public function forget(string $token): void { $this->cache->forget($this->getCacheKey($token)); }
[ "public", "function", "forget", "(", "string", "$", "token", ")", ":", "void", "{", "$", "this", "->", "cache", "->", "forget", "(", "$", "this", "->", "getCacheKey", "(", "$", "token", ")", ")", ";", "}" ]
Forget token. @param string $token
[ "Forget", "token", "." ]
train
https://github.com/mrTimofey/laravel-simple-tokens/blob/b481f56167e00d81a70ba019fe88b055600890a8/src/SimpleProvider.php#L71-L74
mrTimofey/laravel-simple-tokens
src/SimpleProvider.php
SimpleProvider.issueToken
public function issueToken(Authenticatable $user): string { $token = str_random(60); $this->cache->put($this->getCacheKey($token), $user->getAuthIdentifier(), $this->config['token_ttl']); return $token; }
php
public function issueToken(Authenticatable $user): string { $token = str_random(60); $this->cache->put($this->getCacheKey($token), $user->getAuthIdentifier(), $this->config['token_ttl']); return $token; }
[ "public", "function", "issueToken", "(", "Authenticatable", "$", "user", ")", ":", "string", "{", "$", "token", "=", "str_random", "(", "60", ")", ";", "$", "this", "->", "cache", "->", "put", "(", "$", "this", "->", "getCacheKey", "(", "$", "token", ...
Create new token for a model instance and store it in cache. @param Authenticatable $user @return string
[ "Create", "new", "token", "for", "a", "model", "instance", "and", "store", "it", "in", "cache", "." ]
train
https://github.com/mrTimofey/laravel-simple-tokens/blob/b481f56167e00d81a70ba019fe88b055600890a8/src/SimpleProvider.php#L81-L86
joomla-framework/input
src/Input.php
Input.serialize
public function serialize() { // Load all of the inputs. $this->loadAllInputs(); // Remove $_ENV and $_SERVER from the inputs. $inputs = $this->inputs; unset($inputs['env'], $inputs['server']); // Serialize the options, data, and inputs. return serialize(array($this->options, $this->data, $inputs)); }
php
public function serialize() { // Load all of the inputs. $this->loadAllInputs(); // Remove $_ENV and $_SERVER from the inputs. $inputs = $this->inputs; unset($inputs['env'], $inputs['server']); // Serialize the options, data, and inputs. return serialize(array($this->options, $this->data, $inputs)); }
[ "public", "function", "serialize", "(", ")", "{", "// Load all of the inputs.", "$", "this", "->", "loadAllInputs", "(", ")", ";", "// Remove $_ENV and $_SERVER from the inputs.", "$", "inputs", "=", "$", "this", "->", "inputs", ";", "unset", "(", "$", "inputs", ...
Method to serialize the input. @return string The serialized input. @since 1.0
[ "Method", "to", "serialize", "the", "input", "." ]
train
https://github.com/joomla-framework/input/blob/62c28fa6f5f2d754918d6727ea7e24d4affcff11/src/Input.php#L371-L382
joomla-framework/input
src/Input.php
Input.loadAllInputs
protected function loadAllInputs() { if (!self::$loaded) { // Load up all the globals. foreach ($GLOBALS as $global => $data) { // Check if the global starts with an underscore and is allowed. if (strpos($global, '_') === 0 && \in_array(substr($global, 1), self::$allowedGlobals, true)) { // Convert global name to input name. $global = strtolower($global); $global = substr($global, 1); // Get the input. $this->$global; } } self::$loaded = true; } }
php
protected function loadAllInputs() { if (!self::$loaded) { // Load up all the globals. foreach ($GLOBALS as $global => $data) { // Check if the global starts with an underscore and is allowed. if (strpos($global, '_') === 0 && \in_array(substr($global, 1), self::$allowedGlobals, true)) { // Convert global name to input name. $global = strtolower($global); $global = substr($global, 1); // Get the input. $this->$global; } } self::$loaded = true; } }
[ "protected", "function", "loadAllInputs", "(", ")", "{", "if", "(", "!", "self", "::", "$", "loaded", ")", "{", "// Load up all the globals.", "foreach", "(", "$", "GLOBALS", "as", "$", "global", "=>", "$", "data", ")", "{", "// Check if the global starts with...
Method to load all of the global inputs. @return void @since 1.0
[ "Method", "to", "load", "all", "of", "the", "global", "inputs", "." ]
train
https://github.com/joomla-framework/input/blob/62c28fa6f5f2d754918d6727ea7e24d4affcff11/src/Input.php#L416-L437
mintware-de/data-model-mapper
src/ObjectMapper.php
ObjectMapper.map
public function map($rawData, $targetClass) { // Deserialize the data try { if ($this->serializer instanceof SerializerInterface === false) { throw new SerializerException("You've to specify a serializer with the setSerializer() method."); } $data = $this->serializer->deserialize($rawData); } catch (\Exception $e) { throw new SerializerException('Deserialize failed: ' . $e->getMessage(), 0, $e); } // Pre initialize the result $result = null; // Check if the target object is a collection of type X if (substr($targetClass, -2) == '[]') { $result = []; foreach ($data as $key => $entryData) { // Map the data recursive $result[] = $this->mapDataToObject($entryData, substr($targetClass, 0, -2)); } } else { // Map the data recursive $result = $this->mapDataToObject($data, $targetClass); } return $result; }
php
public function map($rawData, $targetClass) { // Deserialize the data try { if ($this->serializer instanceof SerializerInterface === false) { throw new SerializerException("You've to specify a serializer with the setSerializer() method."); } $data = $this->serializer->deserialize($rawData); } catch (\Exception $e) { throw new SerializerException('Deserialize failed: ' . $e->getMessage(), 0, $e); } // Pre initialize the result $result = null; // Check if the target object is a collection of type X if (substr($targetClass, -2) == '[]') { $result = []; foreach ($data as $key => $entryData) { // Map the data recursive $result[] = $this->mapDataToObject($entryData, substr($targetClass, 0, -2)); } } else { // Map the data recursive $result = $this->mapDataToObject($data, $targetClass); } return $result; }
[ "public", "function", "map", "(", "$", "rawData", ",", "$", "targetClass", ")", "{", "// Deserialize the data", "try", "{", "if", "(", "$", "this", "->", "serializer", "instanceof", "SerializerInterface", "===", "false", ")", "{", "throw", "new", "SerializerEx...
Maps raw data to a object @param string $rawData The raw data @param string $targetClass The target object class @return mixed The mapped object @throws SerializerException If the data couldn't be deserialized @throws ClassNotFoundException If the target class does not exist @throws PropertyNotAccessibleException If the class property has no public access an no set-Method @throws TypeMismatchException If The type in the raw data does not match the type in the class @throws \ReflectionException If the target class does not exist
[ "Maps", "raw", "data", "to", "a", "object" ]
train
https://github.com/mintware-de/data-model-mapper/blob/d7dfbaaee208b0c5feb07ff45166c6b5f00adb14/src/ObjectMapper.php#L88-L117
mintware-de/data-model-mapper
src/ObjectMapper.php
ObjectMapper.mapDataToObject
public function mapDataToObject($data, $targetClass) { $targetClass = preg_replace('~(\\\\){2,}~', '\\', $targetClass); // Check if the target object class exists, if not throw an exception if (!class_exists($targetClass)) { throw new ClassNotFoundException($targetClass); } // Create the target object $object = new $targetClass(); // Reflecting the target object to extract properties etc. $class = new \ReflectionClass($targetClass); $attributes = null; if ($data instanceof DeserializedField) { $attributes = $data->attributes; $data = $data->value; } // Iterate over each class property to check if it's mapped foreach ($class->getProperties() as $property) { // Extract the Annotations $fields = $this->reader->getPropertyAnnotations($property); /** @var DataField $field */ foreach ($fields as $field) { if ($field instanceof AttributeHolder) { $this->setPropertyValue($object, $property, $attributes); continue; } if ($field instanceof DataField == false) { continue; } // Check if the property is public accessible or has a setter / adder $propertyName = $property->getName(); $ucw = ucwords($propertyName); if (!$property->isPublic() && !($class->hasMethod('set' . $ucw) || $class->hasMethod('add' . $ucw))) { throw new PropertyNotAccessibleException($propertyName); } if ($field->name == null) { $field->name = $propertyName; } // Check if the current property is defined in the raw data if (!isset($data[$field->name])) { continue; } $currentEntry = $data[$field->name]; $val = null; $types = explode('|', $field->type); $typeKeys = array_keys($types); $lastTypeKey = end($typeKeys); if ($field->preTransformer !== null) { /** @var TransformerInterface $preTransformer */ $preTransformer = $field->preTransformer; $currentEntry = $preTransformer::transform($currentEntry); } if ($field->transformer !== null) { /** @var TransformerInterface $transformer */ $transformer = $field->transformer; $val = $transformer::transform($currentEntry); $types = []; // Ignore type handler! } foreach ($types as $typeKey => $type) { $isLastElement = ($typeKey == $lastTypeKey); // Check the type of the field and set the val if ($type == '') { if ($currentEntry instanceof DeserializedField) { $val = $currentEntry->toPlain(); } else { $val = $currentEntry; } } elseif (in_array($type, $this->primitives)) { $format = ($field instanceof DateTimeField && $field->format !== null ? $field->format : 'Y-m-d\TH:i:s'); $converted = null; try { $converted = $this->castType($currentEntry, $type, $field->name, $format, true); } catch (TypeMismatchException $ex) { if ($isLastElement) { throw $ex; } continue; } $val = $converted; } else { // If none of the primitives match it is an custom object // Check if it's an array of X if (substr($type, -2) == '[]' && (is_array($currentEntry) || ($currentEntry instanceof DeserializedField && is_array($currentEntry->toPlain())))) { $t = substr($type, 0, -2); $val = []; $entries = $currentEntry; if ($entries instanceof DeserializedField) { $entries = $entries->value; if ($field->forceArray && array_keys($entries) != range(0, count($entries) - 1)) { $entries = [$entries]; } } foreach ($entries as $entry) { // Map the data recursive $val[] = (object)$this->mapDataToObject($entry, $t); } } elseif (substr($type, -2) != '[]') { // Map the data recursive $val = (object)$this->mapDataToObject($currentEntry, $type); } } if ($field->postTransformer !== null) { /** @var TransformerInterface $postTransformer */ $postTransformer = $field->postTransformer; $val = $postTransformer::transform($val); } if ($val !== null) { break; } } $this->setPropertyValue($object, $property, $val); } } return $object; }
php
public function mapDataToObject($data, $targetClass) { $targetClass = preg_replace('~(\\\\){2,}~', '\\', $targetClass); // Check if the target object class exists, if not throw an exception if (!class_exists($targetClass)) { throw new ClassNotFoundException($targetClass); } // Create the target object $object = new $targetClass(); // Reflecting the target object to extract properties etc. $class = new \ReflectionClass($targetClass); $attributes = null; if ($data instanceof DeserializedField) { $attributes = $data->attributes; $data = $data->value; } // Iterate over each class property to check if it's mapped foreach ($class->getProperties() as $property) { // Extract the Annotations $fields = $this->reader->getPropertyAnnotations($property); /** @var DataField $field */ foreach ($fields as $field) { if ($field instanceof AttributeHolder) { $this->setPropertyValue($object, $property, $attributes); continue; } if ($field instanceof DataField == false) { continue; } // Check if the property is public accessible or has a setter / adder $propertyName = $property->getName(); $ucw = ucwords($propertyName); if (!$property->isPublic() && !($class->hasMethod('set' . $ucw) || $class->hasMethod('add' . $ucw))) { throw new PropertyNotAccessibleException($propertyName); } if ($field->name == null) { $field->name = $propertyName; } // Check if the current property is defined in the raw data if (!isset($data[$field->name])) { continue; } $currentEntry = $data[$field->name]; $val = null; $types = explode('|', $field->type); $typeKeys = array_keys($types); $lastTypeKey = end($typeKeys); if ($field->preTransformer !== null) { /** @var TransformerInterface $preTransformer */ $preTransformer = $field->preTransformer; $currentEntry = $preTransformer::transform($currentEntry); } if ($field->transformer !== null) { /** @var TransformerInterface $transformer */ $transformer = $field->transformer; $val = $transformer::transform($currentEntry); $types = []; // Ignore type handler! } foreach ($types as $typeKey => $type) { $isLastElement = ($typeKey == $lastTypeKey); // Check the type of the field and set the val if ($type == '') { if ($currentEntry instanceof DeserializedField) { $val = $currentEntry->toPlain(); } else { $val = $currentEntry; } } elseif (in_array($type, $this->primitives)) { $format = ($field instanceof DateTimeField && $field->format !== null ? $field->format : 'Y-m-d\TH:i:s'); $converted = null; try { $converted = $this->castType($currentEntry, $type, $field->name, $format, true); } catch (TypeMismatchException $ex) { if ($isLastElement) { throw $ex; } continue; } $val = $converted; } else { // If none of the primitives match it is an custom object // Check if it's an array of X if (substr($type, -2) == '[]' && (is_array($currentEntry) || ($currentEntry instanceof DeserializedField && is_array($currentEntry->toPlain())))) { $t = substr($type, 0, -2); $val = []; $entries = $currentEntry; if ($entries instanceof DeserializedField) { $entries = $entries->value; if ($field->forceArray && array_keys($entries) != range(0, count($entries) - 1)) { $entries = [$entries]; } } foreach ($entries as $entry) { // Map the data recursive $val[] = (object)$this->mapDataToObject($entry, $t); } } elseif (substr($type, -2) != '[]') { // Map the data recursive $val = (object)$this->mapDataToObject($currentEntry, $type); } } if ($field->postTransformer !== null) { /** @var TransformerInterface $postTransformer */ $postTransformer = $field->postTransformer; $val = $postTransformer::transform($val); } if ($val !== null) { break; } } $this->setPropertyValue($object, $property, $val); } } return $object; }
[ "public", "function", "mapDataToObject", "(", "$", "data", ",", "$", "targetClass", ")", "{", "$", "targetClass", "=", "preg_replace", "(", "'~(\\\\\\\\){2,}~'", ",", "'\\\\'", ",", "$", "targetClass", ")", ";", "// Check if the target object class exists, if not thro...
Maps the current entry to the property of the object @internal @param DeserializedField|array $data The array of data @param string $targetClass The current object class @return mixed The mapped object @throws ClassNotFoundException If the target class does not exist @throws PropertyNotAccessibleException If the mapped property is not accessible @throws TypeMismatchException If the given type in the raw data does not match with the expected type @throws \ReflectionException If the class does not exist. @throws \Exception
[ "Maps", "the", "current", "entry", "to", "the", "property", "of", "the", "object" ]
train
https://github.com/mintware-de/data-model-mapper/blob/d7dfbaaee208b0c5feb07ff45166c6b5f00adb14/src/ObjectMapper.php#L135-L276
mintware-de/data-model-mapper
src/ObjectMapper.php
ObjectMapper.serialize
public function serialize($object, $returnAsString = true) { if ($returnAsString && $this->serializer instanceof SerializerInterface === false) { throw new SerializerException("You've to specify a serializer with the setSerializer() method."); } $dataForSerialization = []; // Reflecting the target object to extract properties etc. $class = new \ReflectionObject($object); $attributes = null; // Iterate over each class property to check if it's mapped foreach ($class->getProperties() as $property) { // Extract the DataField Annotation /** @var AttributeHolder $attributes */ $tmpAttributes = $this->reader->getPropertyAnnotation($property, AttributeHolder::class); if ($tmpAttributes != null && !empty($tmpAttributes)) { $attributes = $this->getPropertyValue($object, $property); } /** @var DataField $field */ $field = $this->reader->getPropertyAnnotation($property, DataField::class); // Is it not defined, the property is not mapped if (null === $field) { continue; } // Check if the property is public accessible or has a setter / adder $propertyName = $property->getName(); $ucw = ucwords($propertyName); if (!$property->isPublic() && !($class->hasMethod('get' . $ucw))) { throw new PropertyNotAccessibleException($propertyName); } if ($field->name == null) { $field->name = $propertyName; } if (isset($dataForSerialization[$field->name]) && $dataForSerialization[$field->name] !== null) { continue; } $val = $this->getPropertyValue($object, $property); // Reverse order on encoding (postTransformer -> transformer -> preTransformer) if ($field->postTransformer !== null) { /** @var TransformerInterface $postTransformer */ $postTransformer = $field->postTransformer; $val = $postTransformer::reverseTransform($val); } if ($field->transformer !== null) { /** @var TransformerInterface $transformer */ $transformer = $field->transformer; $val = $transformer::reverseTransform($val); } if (is_null($val)) { $dataForSerialization[$field->name] = $val; continue; } $currentAttributes = null; if ($field->transformer === null) { $types = explode('|', $field->type); $type = null; foreach ($types as $tString) { $type = $tString; if (!is_object($val) || !in_array(strtolower($tString), $this->primitives)) { break; } } // Check the type of the field and set the val if (in_array($type, $this->primitives)) { $format = 'Y-m-d\TH:i:s'; if ($field instanceof DateTimeField && $field->format !== null) { $format = $field->format; } $val = $this->castType($val, $type, $propertyName, $format); } elseif ($type != null) { // Check if it's an array of X if (substr($type, -2) == '[]' && is_array($val)) { $tmpVal = []; foreach ($val as $entry) { $serialized = $this->serialize($entry, false); // Map the data recursive $tmpVal[] = new PropertyHolder(null, null, (object)$serialized[0], $serialized[1]); } $val = $tmpVal; } elseif (substr($type, -2) != '[]') { $serialized = $this->serialize($val, false); $currentAttributes = $serialized[1]; // Map the data recursive $val = (object)$serialized[0]; } } } if ($field->preTransformer !== null) { /** @var TransformerInterface $preTransformer */ $preTransformer = $field->preTransformer; $val = $preTransformer::reverseTransform($val); } // Assign the raw data to the object property if ($val !== null) { // If the property is public accessible, set the value directly $dataForSerialization[$field->name] = new PropertyHolder($field, $property->name, $val, $currentAttributes); } } $res = $dataForSerialization; if ($returnAsString) { $res = $this->serializer->serialize(new PropertyHolder(null, null, $res, $attributes)); } else { $res = [$dataForSerialization, $attributes]; } return $res; }
php
public function serialize($object, $returnAsString = true) { if ($returnAsString && $this->serializer instanceof SerializerInterface === false) { throw new SerializerException("You've to specify a serializer with the setSerializer() method."); } $dataForSerialization = []; // Reflecting the target object to extract properties etc. $class = new \ReflectionObject($object); $attributes = null; // Iterate over each class property to check if it's mapped foreach ($class->getProperties() as $property) { // Extract the DataField Annotation /** @var AttributeHolder $attributes */ $tmpAttributes = $this->reader->getPropertyAnnotation($property, AttributeHolder::class); if ($tmpAttributes != null && !empty($tmpAttributes)) { $attributes = $this->getPropertyValue($object, $property); } /** @var DataField $field */ $field = $this->reader->getPropertyAnnotation($property, DataField::class); // Is it not defined, the property is not mapped if (null === $field) { continue; } // Check if the property is public accessible or has a setter / adder $propertyName = $property->getName(); $ucw = ucwords($propertyName); if (!$property->isPublic() && !($class->hasMethod('get' . $ucw))) { throw new PropertyNotAccessibleException($propertyName); } if ($field->name == null) { $field->name = $propertyName; } if (isset($dataForSerialization[$field->name]) && $dataForSerialization[$field->name] !== null) { continue; } $val = $this->getPropertyValue($object, $property); // Reverse order on encoding (postTransformer -> transformer -> preTransformer) if ($field->postTransformer !== null) { /** @var TransformerInterface $postTransformer */ $postTransformer = $field->postTransformer; $val = $postTransformer::reverseTransform($val); } if ($field->transformer !== null) { /** @var TransformerInterface $transformer */ $transformer = $field->transformer; $val = $transformer::reverseTransform($val); } if (is_null($val)) { $dataForSerialization[$field->name] = $val; continue; } $currentAttributes = null; if ($field->transformer === null) { $types = explode('|', $field->type); $type = null; foreach ($types as $tString) { $type = $tString; if (!is_object($val) || !in_array(strtolower($tString), $this->primitives)) { break; } } // Check the type of the field and set the val if (in_array($type, $this->primitives)) { $format = 'Y-m-d\TH:i:s'; if ($field instanceof DateTimeField && $field->format !== null) { $format = $field->format; } $val = $this->castType($val, $type, $propertyName, $format); } elseif ($type != null) { // Check if it's an array of X if (substr($type, -2) == '[]' && is_array($val)) { $tmpVal = []; foreach ($val as $entry) { $serialized = $this->serialize($entry, false); // Map the data recursive $tmpVal[] = new PropertyHolder(null, null, (object)$serialized[0], $serialized[1]); } $val = $tmpVal; } elseif (substr($type, -2) != '[]') { $serialized = $this->serialize($val, false); $currentAttributes = $serialized[1]; // Map the data recursive $val = (object)$serialized[0]; } } } if ($field->preTransformer !== null) { /** @var TransformerInterface $preTransformer */ $preTransformer = $field->preTransformer; $val = $preTransformer::reverseTransform($val); } // Assign the raw data to the object property if ($val !== null) { // If the property is public accessible, set the value directly $dataForSerialization[$field->name] = new PropertyHolder($field, $property->name, $val, $currentAttributes); } } $res = $dataForSerialization; if ($returnAsString) { $res = $this->serializer->serialize(new PropertyHolder(null, null, $res, $attributes)); } else { $res = [$dataForSerialization, $attributes]; } return $res; }
[ "public", "function", "serialize", "(", "$", "object", ",", "$", "returnAsString", "=", "true", ")", "{", "if", "(", "$", "returnAsString", "&&", "$", "this", "->", "serializer", "instanceof", "SerializerInterface", "===", "false", ")", "{", "throw", "new", ...
Serializes an object to the raw format @param object $object The object @param bool $returnAsString For internal usage @return mixed|PropertyHolder[] The raw data or an [string => MetaDataValuePair] array @throws ClassNotFoundException If the target class does not exist @throws PropertyNotAccessibleException If the mapped property is not accessible @throws TypeMismatchException If the given type in the raw data does not match with the expected type @throws SerializerException If the data couldn't be serialized
[ "Serializes", "an", "object", "to", "the", "raw", "format" ]
train
https://github.com/mintware-de/data-model-mapper/blob/d7dfbaaee208b0c5feb07ff45166c6b5f00adb14/src/ObjectMapper.php#L290-L413
mintware-de/data-model-mapper
src/ObjectMapper.php
ObjectMapper.castType
private function castType($dataToMap, $type, $propertyName, $datetimeFormat, $fromRaw = false) { $dtCheck = function ($x) { return ($x instanceof \DateTime); }; $checkMethod = [ 'int' => 'is_int', 'integer' => 'is_int', 'float' => 'is_float', 'double' => 'is_float', 'real' => 'is_float', 'bool' => 'is_bool', 'boolean' => 'is_bool', 'date' => $dtCheck, 'datetime' => $dtCheck, 'array' => 'is_array', 'string' => 'is_string', 'object' => function ($x) { return $x == false ? true : $x; }, ]; if (!isset($checkMethod[$type])) { return null; } if ($dataToMap instanceof DeserializedField) { $dataToMap = $dataToMap->toPlain(); } if ($fromRaw && in_array($type, ['date', 'datetime'])) { // Accepts the following formats: // 2017-09-09 // 2017-09-09 13:20:59 // 2017-09-09T13:20:59 // 2017-09-09T13:20:59.511 // 2017-09-09T13:20:59.511Z // 2017-09-09T13:20:59-02:00 $validPattern = '~^\d{4}-\d{2}-\d{2}((T|\s{1})\d{2}:\d{2}:\d{2}(\.\d{1,3}(Z|)|(\+|\-)\d{2}:\d{2}|)|)$~'; $datetimeFormatPattern = preg_quote($datetimeFormat); $repl = [ 'd' => '\d{2}', 'D' => '\w{3}', 'j' => '\d{1,2}', 'l' => '\w*', 'N' => '\d{1}', 'S' => '(st|nd|rd|th)', 'w' => '\d{1}', 'z' => '\d{1,3}', 'W' => '\d{1,2}', 'F' => '\w*', 'm' => '\d{1,2}', 'M' => '\w*', 'n' => '\d{1,2}', 't' => '\d{2}', 'L' => '(0|1)', 'o' => '\d{4}', 'Y' => '\d{4}', 'y' => '\d{2}', 'a' => '(am|pm)', 'A' => '(AM|PM)', 'B' => '\d{3}', 'g' => '\d{1,2}', 'G' => '\d{1,2}', 'h' => '\d{1,2}', 'H' => '\d{1,2}', 'i' => '\d{1,2}', 's' => '\d{1,2}', 'e' => '\w*', 'I' => '(0|1)', 'O' => '(\+|\-)\d{4}', 'P' => '(\+|\-)\d{2}:\d{2}', 'T' => '\w*', 'Z' => '(\-|)\d{1,5}', ]; $datetimeFormatPattern = str_replace(array_keys($repl), array_values($repl), $datetimeFormatPattern); $tmpVal = $dataToMap; if (preg_match($validPattern, $tmpVal)) { $dataToMap = new \DateTime($tmpVal); } elseif ($datetimeFormatPattern != '' && preg_match('~' . $datetimeFormatPattern . '~', $tmpVal)) { $dataToMap = new \DateTime($tmpVal); } else { $casted = intval($tmpVal); if (is_numeric($tmpVal) || ($casted == $tmpVal && strlen($casted) == strlen($tmpVal))) { $dataToMap = new \DateTime(); $dataToMap->setTimestamp($tmpVal); } } } if (!$checkMethod[$type]($dataToMap)) { throw new TypeMismatchException($type, gettype($dataToMap), $propertyName); } if (in_array($type, ['int', 'integer'])) { $dataToMap = (int)$dataToMap; } elseif (in_array($type, ['float', 'double', 'real'])) { $dataToMap = (float)$dataToMap; } elseif (in_array($type, ['bool', 'boolean'])) { $dataToMap = (bool)$dataToMap; } elseif (in_array($type, ['array'])) { $dataToMap = (array)$dataToMap; } elseif (in_array($type, ['string'])) { $dataToMap = (string)$dataToMap; } elseif (in_array($type, ['object'])) { $tmpVal = $dataToMap; if (is_array($tmpVal) && array_keys($tmpVal) != range(0, count($tmpVal))) { $dataToMap = (object)$tmpVal; } if (!is_object($dataToMap)) { throw new TypeMismatchException($type, gettype($dataToMap), $propertyName); } $dataToMap = (object)$dataToMap; } elseif (in_array($type, ['date', 'datetime'])) { if ($fromRaw) { if (strtolower($type) == 'date') { $dataToMap->setTime(0, 0, 0); } } else { /** @var \DateTime $dataToMap */ if (strtolower($datetimeFormat) !== 'timestamp') { $dataToMap = $dataToMap->format($datetimeFormat); } else { $dataToMap = $dataToMap->getTimestamp(); } } } return $dataToMap; }
php
private function castType($dataToMap, $type, $propertyName, $datetimeFormat, $fromRaw = false) { $dtCheck = function ($x) { return ($x instanceof \DateTime); }; $checkMethod = [ 'int' => 'is_int', 'integer' => 'is_int', 'float' => 'is_float', 'double' => 'is_float', 'real' => 'is_float', 'bool' => 'is_bool', 'boolean' => 'is_bool', 'date' => $dtCheck, 'datetime' => $dtCheck, 'array' => 'is_array', 'string' => 'is_string', 'object' => function ($x) { return $x == false ? true : $x; }, ]; if (!isset($checkMethod[$type])) { return null; } if ($dataToMap instanceof DeserializedField) { $dataToMap = $dataToMap->toPlain(); } if ($fromRaw && in_array($type, ['date', 'datetime'])) { // Accepts the following formats: // 2017-09-09 // 2017-09-09 13:20:59 // 2017-09-09T13:20:59 // 2017-09-09T13:20:59.511 // 2017-09-09T13:20:59.511Z // 2017-09-09T13:20:59-02:00 $validPattern = '~^\d{4}-\d{2}-\d{2}((T|\s{1})\d{2}:\d{2}:\d{2}(\.\d{1,3}(Z|)|(\+|\-)\d{2}:\d{2}|)|)$~'; $datetimeFormatPattern = preg_quote($datetimeFormat); $repl = [ 'd' => '\d{2}', 'D' => '\w{3}', 'j' => '\d{1,2}', 'l' => '\w*', 'N' => '\d{1}', 'S' => '(st|nd|rd|th)', 'w' => '\d{1}', 'z' => '\d{1,3}', 'W' => '\d{1,2}', 'F' => '\w*', 'm' => '\d{1,2}', 'M' => '\w*', 'n' => '\d{1,2}', 't' => '\d{2}', 'L' => '(0|1)', 'o' => '\d{4}', 'Y' => '\d{4}', 'y' => '\d{2}', 'a' => '(am|pm)', 'A' => '(AM|PM)', 'B' => '\d{3}', 'g' => '\d{1,2}', 'G' => '\d{1,2}', 'h' => '\d{1,2}', 'H' => '\d{1,2}', 'i' => '\d{1,2}', 's' => '\d{1,2}', 'e' => '\w*', 'I' => '(0|1)', 'O' => '(\+|\-)\d{4}', 'P' => '(\+|\-)\d{2}:\d{2}', 'T' => '\w*', 'Z' => '(\-|)\d{1,5}', ]; $datetimeFormatPattern = str_replace(array_keys($repl), array_values($repl), $datetimeFormatPattern); $tmpVal = $dataToMap; if (preg_match($validPattern, $tmpVal)) { $dataToMap = new \DateTime($tmpVal); } elseif ($datetimeFormatPattern != '' && preg_match('~' . $datetimeFormatPattern . '~', $tmpVal)) { $dataToMap = new \DateTime($tmpVal); } else { $casted = intval($tmpVal); if (is_numeric($tmpVal) || ($casted == $tmpVal && strlen($casted) == strlen($tmpVal))) { $dataToMap = new \DateTime(); $dataToMap->setTimestamp($tmpVal); } } } if (!$checkMethod[$type]($dataToMap)) { throw new TypeMismatchException($type, gettype($dataToMap), $propertyName); } if (in_array($type, ['int', 'integer'])) { $dataToMap = (int)$dataToMap; } elseif (in_array($type, ['float', 'double', 'real'])) { $dataToMap = (float)$dataToMap; } elseif (in_array($type, ['bool', 'boolean'])) { $dataToMap = (bool)$dataToMap; } elseif (in_array($type, ['array'])) { $dataToMap = (array)$dataToMap; } elseif (in_array($type, ['string'])) { $dataToMap = (string)$dataToMap; } elseif (in_array($type, ['object'])) { $tmpVal = $dataToMap; if (is_array($tmpVal) && array_keys($tmpVal) != range(0, count($tmpVal))) { $dataToMap = (object)$tmpVal; } if (!is_object($dataToMap)) { throw new TypeMismatchException($type, gettype($dataToMap), $propertyName); } $dataToMap = (object)$dataToMap; } elseif (in_array($type, ['date', 'datetime'])) { if ($fromRaw) { if (strtolower($type) == 'date') { $dataToMap->setTime(0, 0, 0); } } else { /** @var \DateTime $dataToMap */ if (strtolower($datetimeFormat) !== 'timestamp') { $dataToMap = $dataToMap->format($datetimeFormat); } else { $dataToMap = $dataToMap->getTimestamp(); } } } return $dataToMap; }
[ "private", "function", "castType", "(", "$", "dataToMap", ",", "$", "type", ",", "$", "propertyName", ",", "$", "datetimeFormat", ",", "$", "fromRaw", "=", "false", ")", "{", "$", "dtCheck", "=", "function", "(", "$", "x", ")", "{", "return", "(", "$...
@param mixed $dataToMap The data which should be mapped @param string $type The target type @param string $propertyName The name of the property (required for the exception) @param string $datetimeFormat the format for DateTime deserialization @param bool $fromRaw True, if the data comes from the raw data @return mixed @throws TypeMismatchException If the data does not match to the type @throws \Exception If something went wrong during date casting @internal
[ "@param", "mixed", "$dataToMap", "The", "data", "which", "should", "be", "mapped", "@param", "string", "$type", "The", "target", "type", "@param", "string", "$propertyName", "The", "name", "of", "the", "property", "(", "required", "for", "the", "exception", ")...
train
https://github.com/mintware-de/data-model-mapper/blob/d7dfbaaee208b0c5feb07ff45166c6b5f00adb14/src/ObjectMapper.php#L427-L554
mintware-de/data-model-mapper
src/ObjectMapper.php
ObjectMapper.setPropertyValue
protected function setPropertyValue($object, \ReflectionProperty $property, $value) { if ($value !== null) { // If the property is public accessible, set the value directly if ($property->isPublic()) { $object->{$property->name} = $value; } else { // If not, use the setter / adder $ucw = ucwords($property->name); if ($property->getDeclaringClass()->hasMethod($method = 'set' . $ucw)) { $object->$method($value); } elseif ($property->getDeclaringClass()->hasMethod($method = 'add' . $ucw)) { $object->$method($value); } } } }
php
protected function setPropertyValue($object, \ReflectionProperty $property, $value) { if ($value !== null) { // If the property is public accessible, set the value directly if ($property->isPublic()) { $object->{$property->name} = $value; } else { // If not, use the setter / adder $ucw = ucwords($property->name); if ($property->getDeclaringClass()->hasMethod($method = 'set' . $ucw)) { $object->$method($value); } elseif ($property->getDeclaringClass()->hasMethod($method = 'add' . $ucw)) { $object->$method($value); } } } }
[ "protected", "function", "setPropertyValue", "(", "$", "object", ",", "\\", "ReflectionProperty", "$", "property", ",", "$", "value", ")", "{", "if", "(", "$", "value", "!==", "null", ")", "{", "// If the property is public accessible, set the value directly", "if",...
Sets a property of an object @param object $object The object @param \ReflectionProperty $property The Property @param mixed $value The new value
[ "Sets", "a", "property", "of", "an", "object" ]
train
https://github.com/mintware-de/data-model-mapper/blob/d7dfbaaee208b0c5feb07ff45166c6b5f00adb14/src/ObjectMapper.php#L581-L597
marvin255/bxcodegen
src/generator/Component.php
Component.collectDataFromInputForTemplate
protected function collectDataFromInputForTemplate(CollectionInterface $options) { $name = $options->get('name'); if (!$name) { throw new InvalidArgumentException( 'Name option must be a non empty string' ); } if (mb_strpos($name, ':') === false && $options->get('default_namespace')) { $name = $options->get('default_namespace') . ':' . $name; } if (!preg_match('/^([a-zA-Z0-9_\.]{3,}):([a-zA-Z0-9_\.]{3,})$/', $name, $nameParts)) { throw new InvalidArgumentException( "Name option must be in format namespace:name, got: {$name}" ); } $nameParts = array_map('strtolower', $nameParts); $namespace = implode('', array_map('ucfirst', explode('.', $nameParts[1]))); $className = implode('', array_map('ucfirst', preg_split('/(\.|_)/', $nameParts[2]))); $return = [ 'full_component_name' => $name, 'php_namespace' => $namespace, 'php_class' => $className, 'component_namespace' => $nameParts[1], 'component_name' => $nameParts[2], 'readable_title' => $options->get( 'title', str_replace('.', ' ', ucfirst($nameParts[2])) ), ]; return $return; }
php
protected function collectDataFromInputForTemplate(CollectionInterface $options) { $name = $options->get('name'); if (!$name) { throw new InvalidArgumentException( 'Name option must be a non empty string' ); } if (mb_strpos($name, ':') === false && $options->get('default_namespace')) { $name = $options->get('default_namespace') . ':' . $name; } if (!preg_match('/^([a-zA-Z0-9_\.]{3,}):([a-zA-Z0-9_\.]{3,})$/', $name, $nameParts)) { throw new InvalidArgumentException( "Name option must be in format namespace:name, got: {$name}" ); } $nameParts = array_map('strtolower', $nameParts); $namespace = implode('', array_map('ucfirst', explode('.', $nameParts[1]))); $className = implode('', array_map('ucfirst', preg_split('/(\.|_)/', $nameParts[2]))); $return = [ 'full_component_name' => $name, 'php_namespace' => $namespace, 'php_class' => $className, 'component_namespace' => $nameParts[1], 'component_name' => $nameParts[2], 'readable_title' => $options->get( 'title', str_replace('.', ' ', ucfirst($nameParts[2])) ), ]; return $return; }
[ "protected", "function", "collectDataFromInputForTemplate", "(", "CollectionInterface", "$", "options", ")", "{", "$", "name", "=", "$", "options", "->", "get", "(", "'name'", ")", ";", "if", "(", "!", "$", "name", ")", "{", "throw", "new", "InvalidArgumentE...
Собирает массив опций для шаблонов из тех опций, что пришли от пользователя. @param \marvin255\bxcodegen\service\options\CollectionInterface $options @return array @throws \InvalidArgumentException
[ "Собирает", "массив", "опций", "для", "шаблонов", "из", "тех", "опций", "что", "пришли", "от", "пользователя", "." ]
train
https://github.com/marvin255/bxcodegen/blob/2afa44426aa40c9cbfcdae745367d9dafd4d2f9f/src/generator/Component.php#L50-L87
chocoboxxf/yii2-qiniu-sdk
src/Qiniu.php
Qiniu.put
public function put($fileName, $fileData) { if (!isset($this->managers['upload'])) { $this->managers['upload'] = new UploadManager(); } $uploadToken = $this->auth->uploadToken($this->bucket); list($ret, $err) = $this->managers['upload']->put($uploadToken, $fileName, $fileData); // 正常情况 if (is_null($err)) { return [ 'code' => self::CODE_SUCCESS, 'message' => self::MESSAGE_SUCCESS, 'result' => [ 'hash' => $ret['hash'], 'key' => $ret['key'], 'url' => sprintf('%s%s/%s', $this->secure ? 'https://' : 'http://', rtrim($this->domain, '/'), $fileName ), ], ]; } // 错误情况 return [ 'code' => $err->code(), 'message' => $err->message(), 'result' => [ 'hash' => '', 'key' => '', 'url' => '', ], ]; }
php
public function put($fileName, $fileData) { if (!isset($this->managers['upload'])) { $this->managers['upload'] = new UploadManager(); } $uploadToken = $this->auth->uploadToken($this->bucket); list($ret, $err) = $this->managers['upload']->put($uploadToken, $fileName, $fileData); // 正常情况 if (is_null($err)) { return [ 'code' => self::CODE_SUCCESS, 'message' => self::MESSAGE_SUCCESS, 'result' => [ 'hash' => $ret['hash'], 'key' => $ret['key'], 'url' => sprintf('%s%s/%s', $this->secure ? 'https://' : 'http://', rtrim($this->domain, '/'), $fileName ), ], ]; } // 错误情况 return [ 'code' => $err->code(), 'message' => $err->message(), 'result' => [ 'hash' => '', 'key' => '', 'url' => '', ], ]; }
[ "public", "function", "put", "(", "$", "fileName", ",", "$", "fileData", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "managers", "[", "'upload'", "]", ")", ")", "{", "$", "this", "->", "managers", "[", "'upload'", "]", "=", "new", ...
使用文件内容上传 @param string $fileName 目标文件名 @param string $fileData 文件内容 @return mixed
[ "使用文件内容上传" ]
train
https://github.com/chocoboxxf/yii2-qiniu-sdk/blob/489e883c9c8c2bbb4a27c52a1654ea78fdab57b5/src/Qiniu.php#L61-L94
chocoboxxf/yii2-qiniu-sdk
src/Qiniu.php
Qiniu.batchDownload
public function batchDownload($fileNameList = [], $realDownload = false, $downloadPath = '') { if (empty($fileNameList)) { return []; } $result = []; foreach ($fileNameList as $fileName) { $result[$fileName] = $this->auth->privateDownloadUrl($fileName); } // 仅返回下载链接 if (!$realDownload) { return $result; } // 下载文件 if (trim($downloadPath) === '') { $downloadPath = __DIR__; } // 创建目录 if (!is_dir($downloadPath)) { mkdir($downloadPath, 0777, true); } foreach ($result as $fileName => $url) { $name = substr($fileName, strrpos($fileName, '/') + 1); file_put_contents($downloadPath.'/'.$name, file_get_contents($url)); } return $result; }
php
public function batchDownload($fileNameList = [], $realDownload = false, $downloadPath = '') { if (empty($fileNameList)) { return []; } $result = []; foreach ($fileNameList as $fileName) { $result[$fileName] = $this->auth->privateDownloadUrl($fileName); } // 仅返回下载链接 if (!$realDownload) { return $result; } // 下载文件 if (trim($downloadPath) === '') { $downloadPath = __DIR__; } // 创建目录 if (!is_dir($downloadPath)) { mkdir($downloadPath, 0777, true); } foreach ($result as $fileName => $url) { $name = substr($fileName, strrpos($fileName, '/') + 1); file_put_contents($downloadPath.'/'.$name, file_get_contents($url)); } return $result; }
[ "public", "function", "batchDownload", "(", "$", "fileNameList", "=", "[", "]", ",", "$", "realDownload", "=", "false", ",", "$", "downloadPath", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "fileNameList", ")", ")", "{", "return", "[", "]", ";...
批量生成私有文件下载链接,并直接下载到本地路径 @param array $fileNameList 私有文件链接 @param bool|false $realDownload 是否直接下载 @param string $downloadPath 下载文件保存路径 @return array 下载文件链接列表,key为私有文件链接,value为临时下载链接
[ "批量生成私有文件下载链接,并直接下载到本地路径" ]
train
https://github.com/chocoboxxf/yii2-qiniu-sdk/blob/489e883c9c8c2bbb4a27c52a1654ea78fdab57b5/src/Qiniu.php#L145-L171
chocoboxxf/yii2-qiniu-sdk
src/Qiniu.php
Qiniu.uploadToken
public function uploadToken( $bucket = null, $key = null, $expires = 3600, $policy = null) { // 默认使用当前配置的bucket if ($bucket === null) { $bucket = $this->bucket; } return $this->auth->uploadToken( $bucket, $key, $expires, $policy, true ); }
php
public function uploadToken( $bucket = null, $key = null, $expires = 3600, $policy = null) { // 默认使用当前配置的bucket if ($bucket === null) { $bucket = $this->bucket; } return $this->auth->uploadToken( $bucket, $key, $expires, $policy, true ); }
[ "public", "function", "uploadToken", "(", "$", "bucket", "=", "null", ",", "$", "key", "=", "null", ",", "$", "expires", "=", "3600", ",", "$", "policy", "=", "null", ")", "{", "// 默认使用当前配置的bucket", "if", "(", "$", "bucket", "===", "null", ")", "{", ...
获取上传凭证 @param string|null $bucket @param string|null $key @param int $expires @param array|null $policy @return mixed
[ "获取上传凭证" ]
train
https://github.com/chocoboxxf/yii2-qiniu-sdk/blob/489e883c9c8c2bbb4a27c52a1654ea78fdab57b5/src/Qiniu.php#L181-L198
budde377/Part
lib/view/page_element/TopMenuPageElementImpl.php
TopMenuPageElementImpl.generateContent
public function generateContent() { parent::generateContent(); $out = ""; $pageOrder = $this->pageOrder->getPageOrder(); /** @var $page Page */ foreach($pageOrder as $page){ $id = $page->getID(); $active = $this->currentPage === $page?"class='active'":""; $hidden = $page->isHidden()?'hidden':''; $out .= " <li $active $hidden> <a href='/$id'>{$page->getTitle()}</a> </li> "; } return "<ul>$out</ul>"; }
php
public function generateContent() { parent::generateContent(); $out = ""; $pageOrder = $this->pageOrder->getPageOrder(); /** @var $page Page */ foreach($pageOrder as $page){ $id = $page->getID(); $active = $this->currentPage === $page?"class='active'":""; $hidden = $page->isHidden()?'hidden':''; $out .= " <li $active $hidden> <a href='/$id'>{$page->getTitle()}</a> </li> "; } return "<ul>$out</ul>"; }
[ "public", "function", "generateContent", "(", ")", "{", "parent", "::", "generateContent", "(", ")", ";", "$", "out", "=", "\"\"", ";", "$", "pageOrder", "=", "$", "this", "->", "pageOrder", "->", "getPageOrder", "(", ")", ";", "/** @var $page Page */", "f...
This will return content from page element as a string. The format can be xml, xhtml, html etc. but return type must be string @return string
[ "This", "will", "return", "content", "from", "page", "element", "as", "a", "string", ".", "The", "format", "can", "be", "xml", "xhtml", "html", "etc", ".", "but", "return", "type", "must", "be", "string" ]
train
https://github.com/budde377/Part/blob/9ab5ce43dd809f9c563040ae0f7dcb7f56a52c5d/lib/view/page_element/TopMenuPageElementImpl.php#L28-L46
willmorgan/silverstripe-cropperfield
code/Cropper/GenericCropper.php
GenericCropper.getAspectRatio
public function getAspectRatio() { if(isset($this->aspectRatio)) { return $this->aspectRatio; } $impliedAspect = $this->getCropWidth() / $this->getCropHeight(); return $impliedAspect; }
php
public function getAspectRatio() { if(isset($this->aspectRatio)) { return $this->aspectRatio; } $impliedAspect = $this->getCropWidth() / $this->getCropHeight(); return $impliedAspect; }
[ "public", "function", "getAspectRatio", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "aspectRatio", ")", ")", "{", "return", "$", "this", "->", "aspectRatio", ";", "}", "$", "impliedAspect", "=", "$", "this", "->", "getCropWidth", "(", ")...
Look at the aspect ratio. If there's none, then set it from the implied crop width/height.
[ "Look", "at", "the", "aspect", "ratio", ".", "If", "there", "s", "none", "then", "set", "it", "from", "the", "implied", "crop", "width", "/", "height", "." ]
train
https://github.com/willmorgan/silverstripe-cropperfield/blob/855ca4f44dd392b1cf9d36f411a2c145b4b3d975/code/Cropper/GenericCropper.php#L164-L170