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
datasift/datasift-php
lib/DataSift/Account.php
DataSift_Account.usage
public function usage($start = false, $end = false, $period = null) { $params = array(); if ($start) { $params['start'] = $start; } if ($end) { $params['end'] = $end; } if (isset($period)) { $params['period'] = $period; } return $this->_user->get('account/usage', $params); }
php
public function usage($start = false, $end = false, $period = null) { $params = array(); if ($start) { $params['start'] = $start; } if ($end) { $params['end'] = $end; } if (isset($period)) { $params['period'] = $period; } return $this->_user->get('account/usage', $params); }
[ "public", "function", "usage", "(", "$", "start", "=", "false", ",", "$", "end", "=", "false", ",", "$", "period", "=", "null", ")", "{", "$", "params", "=", "array", "(", ")", ";", "if", "(", "$", "start", ")", "{", "$", "params", "[", "'start'", "]", "=", "$", "start", ";", "}", "if", "(", "$", "end", ")", "{", "$", "params", "[", "'end'", "]", "=", "$", "end", ";", "}", "if", "(", "isset", "(", "$", "period", ")", ")", "{", "$", "params", "[", "'period'", "]", "=", "$", "period", ";", "}", "return", "$", "this", "->", "_user", "->", "get", "(", "'account/usage'", ",", "$", "params", ")", ";", "}" ]
Returns the user agent this library should use for all API calls. @return string
[ "Returns", "the", "user", "agent", "this", "library", "should", "use", "for", "all", "API", "calls", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Account.php#L57-L72
crossjoin/Css
src/Crossjoin/Css/Format/Rule/TraitDeclarations.php
TraitDeclarations.setDeclarations
public function setDeclarations($declarations) { $this->declarations = []; if (!is_array($declarations)) { $declarations = [$declarations]; } foreach ($declarations as $declaration) { $this->addDeclaration($declaration); } return $this; }
php
public function setDeclarations($declarations) { $this->declarations = []; if (!is_array($declarations)) { $declarations = [$declarations]; } foreach ($declarations as $declaration) { $this->addDeclaration($declaration); } return $this; }
[ "public", "function", "setDeclarations", "(", "$", "declarations", ")", "{", "$", "this", "->", "declarations", "=", "[", "]", ";", "if", "(", "!", "is_array", "(", "$", "declarations", ")", ")", "{", "$", "declarations", "=", "[", "$", "declarations", "]", ";", "}", "foreach", "(", "$", "declarations", "as", "$", "declaration", ")", "{", "$", "this", "->", "addDeclaration", "(", "$", "declaration", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the declarations. @param DeclarationAbstract[]|DeclarationAbstract $declarations @return $this
[ "Sets", "the", "declarations", "." ]
train
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Format/Rule/TraitDeclarations.php#L17-L28
Atlantic18/CoralCoreBundle
Service/Request/Response.php
Response.parserHttpHeadersAsArray
protected function parserHttpHeadersAsArray($rawHeaders) { $headers = array(); foreach(explode("\n", $rawHeaders) as $i => $line) { if($i == 0) { $headers['HTTP_STATUS'] = substr($line, 9, 3); } else { list($key, $value) = explode(': ', $line); $headers[trim($key)] = trim($value); } } return $headers; }
php
protected function parserHttpHeadersAsArray($rawHeaders) { $headers = array(); foreach(explode("\n", $rawHeaders) as $i => $line) { if($i == 0) { $headers['HTTP_STATUS'] = substr($line, 9, 3); } else { list($key, $value) = explode(': ', $line); $headers[trim($key)] = trim($value); } } return $headers; }
[ "protected", "function", "parserHttpHeadersAsArray", "(", "$", "rawHeaders", ")", "{", "$", "headers", "=", "array", "(", ")", ";", "foreach", "(", "explode", "(", "\"\\n\"", ",", "$", "rawHeaders", ")", "as", "$", "i", "=>", "$", "line", ")", "{", "if", "(", "$", "i", "==", "0", ")", "{", "$", "headers", "[", "'HTTP_STATUS'", "]", "=", "substr", "(", "$", "line", ",", "9", ",", "3", ")", ";", "}", "else", "{", "list", "(", "$", "key", ",", "$", "value", ")", "=", "explode", "(", "': '", ",", "$", "line", ")", ";", "$", "headers", "[", "trim", "(", "$", "key", ")", "]", "=", "trim", "(", "$", "value", ")", ";", "}", "}", "return", "$", "headers", ";", "}" ]
Convert string headers into an array @param string $rawHeaders @return array HTTP Headers
[ "Convert", "string", "headers", "into", "an", "array" ]
train
https://github.com/Atlantic18/CoralCoreBundle/blob/7d74ffaf51046ad13cbfc2b0b69d656a499f38ab/Service/Request/Response.php#L51-L69
esperecyan/dictionary-php
src/parser/GenericDictionaryParser.php
GenericDictionaryParser.convertToCSVRecord
public function convertToCSVRecord(array $fields): string { $csv = new \SplTempFileObject(); $csv->fputcsv($fields); $csv->rewind(); return rtrim($csv->fgets(), "\r\n"); }
php
public function convertToCSVRecord(array $fields): string { $csv = new \SplTempFileObject(); $csv->fputcsv($fields); $csv->rewind(); return rtrim($csv->fgets(), "\r\n"); }
[ "public", "function", "convertToCSVRecord", "(", "array", "$", "fields", ")", ":", "string", "{", "$", "csv", "=", "new", "\\", "SplTempFileObject", "(", ")", ";", "$", "csv", "->", "fputcsv", "(", "$", "fields", ")", ";", "$", "csv", "->", "rewind", "(", ")", ";", "return", "rtrim", "(", "$", "csv", "->", "fgets", "(", ")", ",", "\"\\r\\n\"", ")", ";", "}" ]
配列をCSVレコード風の文字列に変換して返します。 @param string[] $fields @return string
[ "配列をCSVレコード風の文字列に変換して返します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/GenericDictionaryParser.php#L68-L74
esperecyan/dictionary-php
src/parser/GenericDictionaryParser.php
GenericDictionaryParser.addRecord
protected function addRecord(Dictionary $dictionary, array $fieldNames, array $fields, bool $first) { if (!in_array('text', $fieldNames)) { throw new SyntaxException( sprintf(_('ヘッダ行「%s」にフィールド名「text」が存在しません'), $this->convertToCSVRecord($fieldNames)) ); } if (count($fields) > count($fieldNames)) { throw new SyntaxException( sprintf(_('「%s」のフィールド数は、ヘッダ行のフィールド名の数を超えています。'), $this->convertToCSVRecord($fields)) ); } foreach ($fields as $i => $field) { if ($field !== '') { if ($fieldNames[$i][0] === '@') { if ($first) { $metaFields[$fieldNames[$i]] = $field; } else { $this->logger->error(sprintf(_('メタフィールド%sの内容は、最初のレコードにのみ記述可能です。'), $fieldNames[$i])); } } else { $fieldsAsMultiDimensionalArray[$fieldNames[$i]][] = $field; } } } if (!isset($fieldsAsMultiDimensionalArray['text'][0])) { throw new SyntaxException( sprintf(_('「%s」にはtextフィールドが存在しません。'), $this->convertToCSVRecord($fields)) ); } $dictionary->addWord($fieldsAsMultiDimensionalArray); if (isset($metaFields)) { $dictionary->setMetadata($metaFields); } }
php
protected function addRecord(Dictionary $dictionary, array $fieldNames, array $fields, bool $first) { if (!in_array('text', $fieldNames)) { throw new SyntaxException( sprintf(_('ヘッダ行「%s」にフィールド名「text」が存在しません'), $this->convertToCSVRecord($fieldNames)) ); } if (count($fields) > count($fieldNames)) { throw new SyntaxException( sprintf(_('「%s」のフィールド数は、ヘッダ行のフィールド名の数を超えています。'), $this->convertToCSVRecord($fields)) ); } foreach ($fields as $i => $field) { if ($field !== '') { if ($fieldNames[$i][0] === '@') { if ($first) { $metaFields[$fieldNames[$i]] = $field; } else { $this->logger->error(sprintf(_('メタフィールド%sの内容は、最初のレコードにのみ記述可能です。'), $fieldNames[$i])); } } else { $fieldsAsMultiDimensionalArray[$fieldNames[$i]][] = $field; } } } if (!isset($fieldsAsMultiDimensionalArray['text'][0])) { throw new SyntaxException( sprintf(_('「%s」にはtextフィールドが存在しません。'), $this->convertToCSVRecord($fields)) ); } $dictionary->addWord($fieldsAsMultiDimensionalArray); if (isset($metaFields)) { $dictionary->setMetadata($metaFields); } }
[ "protected", "function", "addRecord", "(", "Dictionary", "$", "dictionary", ",", "array", "$", "fieldNames", ",", "array", "$", "fields", ",", "bool", "$", "first", ")", "{", "if", "(", "!", "in_array", "(", "'text'", ",", "$", "fieldNames", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'ヘッダ行「%s」にフィールド名「text」が存在しません'), $this->convertToCSVRecord($fieldNames))", "", "", "", "", "", "", "", "", "", "", "", ")", ";", "}", "if", "(", "count", "(", "$", "fields", ")", ">", "count", "(", "$", "fieldNames", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%s」のフィールド数は、ヘッダ行のフィールド名の数を超えています。'), $this->convertToCSVRecord($fields))", "", "", "", "", "", "", "", "", "", "", "", ")", ";", "}", "foreach", "(", "$", "fields", "as", "$", "i", "=>", "$", "field", ")", "{", "if", "(", "$", "field", "!==", "''", ")", "{", "if", "(", "$", "fieldNames", "[", "$", "i", "]", "[", "0", "]", "===", "'@'", ")", "{", "if", "(", "$", "first", ")", "{", "$", "metaFields", "[", "$", "fieldNames", "[", "$", "i", "]", "]", "=", "$", "field", ";", "}", "else", "{", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "_", "(", "'メタフィールド%sの内容は、最初のレコードにのみ記述可能です。'), $fieldNames[$i]));", "", "", "", "", "", "", "", "", "", "", "", "}", "}", "else", "{", "$", "fieldsAsMultiDimensionalArray", "[", "$", "fieldNames", "[", "$", "i", "]", "]", "[", "]", "=", "$", "field", ";", "}", "}", "}", "if", "(", "!", "isset", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'text'", "]", "[", "0", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%s」にはtextフィールドが存在しません。'), $this->convertToCSVRecord($fiel", "d", "s", ")", "", "", "", "", "", "", "", "", ")", ";", "}", "$", "dictionary", "->", "addWord", "(", "$", "fieldsAsMultiDimensionalArray", ")", ";", "if", "(", "isset", "(", "$", "metaFields", ")", ")", "{", "$", "dictionary", "->", "setMetadata", "(", "$", "metaFields", ")", ";", "}", "}" ]
CSVの一レコードを表す2つの配列によってお題を追加します。 @param Dictionary $dictionary @param string[] $fieldNames @param string[] $fields @param bool $first ヘッダ行を除く最初のレコードであれば真。 @throws SyntaxException
[ "CSVの一レコードを表す2つの配列によってお題を追加します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/GenericDictionaryParser.php#L84-L122
esperecyan/dictionary-php
src/parser/GenericDictionaryParser.php
GenericDictionaryParser.correctEncoding
public function correctEncoding(string $binary): string { if (mb_check_encoding($binary, 'UTF-8')) { $fromEncoding = 'UTF-8'; } else { $fromEncoding = mb_detect_encoding($binary, self::ENCODING_DETECTION_ORDER); if (!$fromEncoding) { throw new SyntaxException(_('CSVファイルの符号化方式 (文字コード) の検出に失敗しました。') . _('CSVファイルの符号化方式 (文字コード) は UTF-8 でなければなりません。')); } $this->logger->error(_('CSVファイルの符号化方式 (文字コード) は UTF-8 でなければなりません。')); } return mb_convert_encoding($binary, 'UTF-8', $fromEncoding); }
php
public function correctEncoding(string $binary): string { if (mb_check_encoding($binary, 'UTF-8')) { $fromEncoding = 'UTF-8'; } else { $fromEncoding = mb_detect_encoding($binary, self::ENCODING_DETECTION_ORDER); if (!$fromEncoding) { throw new SyntaxException(_('CSVファイルの符号化方式 (文字コード) の検出に失敗しました。') . _('CSVファイルの符号化方式 (文字コード) は UTF-8 でなければなりません。')); } $this->logger->error(_('CSVファイルの符号化方式 (文字コード) は UTF-8 でなければなりません。')); } return mb_convert_encoding($binary, 'UTF-8', $fromEncoding); }
[ "public", "function", "correctEncoding", "(", "string", "$", "binary", ")", ":", "string", "{", "if", "(", "mb_check_encoding", "(", "$", "binary", ",", "'UTF-8'", ")", ")", "{", "$", "fromEncoding", "=", "'UTF-8'", ";", "}", "else", "{", "$", "fromEncoding", "=", "mb_detect_encoding", "(", "$", "binary", ",", "self", "::", "ENCODING_DETECTION_ORDER", ")", ";", "if", "(", "!", "$", "fromEncoding", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'CSVファイルの符号化方式 (文字コード) の検出に失敗しました。')", "", ".", "_", "(", "'CSVファイルの符号化方式 (文字コード) は UTF-8 でなければなりません。'));", "", "", "", "}", "$", "this", "->", "logger", "->", "error", "(", "_", "(", "'CSVファイルの符号化方式 (文字コード) は UTF-8 でなければなりません。'));", "", "", "", "}", "return", "mb_convert_encoding", "(", "$", "binary", ",", "'UTF-8'", ",", "$", "fromEncoding", ")", ";", "}" ]
符号化方式をUTF-8に矯正します。 @param string $binary @throws SyntaxException 符号化方式の検出に失敗した場合。 @return string
[ "符号化方式をUTF", "-", "8に矯正します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/GenericDictionaryParser.php#L140-L153
esperecyan/dictionary-php
src/parser/GenericDictionaryParser.php
GenericDictionaryParser.generateTempFile
public function generateTempFile($file = null): string { $path = tempnam(sys_get_temp_dir(), self::TEMP_FILE_OR_DIRECTORY_PREFIX); if ($file) { file_put_contents($path, $file instanceof \SplFileInfo ? (new Parser())->getBinary($file) : $file); } register_shutdown_function(function () use ($path) { if (file_exists($path)) { unlink($path); } }); return $path; }
php
public function generateTempFile($file = null): string { $path = tempnam(sys_get_temp_dir(), self::TEMP_FILE_OR_DIRECTORY_PREFIX); if ($file) { file_put_contents($path, $file instanceof \SplFileInfo ? (new Parser())->getBinary($file) : $file); } register_shutdown_function(function () use ($path) { if (file_exists($path)) { unlink($path); } }); return $path; }
[ "public", "function", "generateTempFile", "(", "$", "file", "=", "null", ")", ":", "string", "{", "$", "path", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "self", "::", "TEMP_FILE_OR_DIRECTORY_PREFIX", ")", ";", "if", "(", "$", "file", ")", "{", "file_put_contents", "(", "$", "path", ",", "$", "file", "instanceof", "\\", "SplFileInfo", "?", "(", "new", "Parser", "(", ")", ")", "->", "getBinary", "(", "$", "file", ")", ":", "$", "file", ")", ";", "}", "register_shutdown_function", "(", "function", "(", ")", "use", "(", "$", "path", ")", "{", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "unlink", "(", "$", "path", ")", ";", "}", "}", ")", ";", "return", "$", "path", ";", "}" ]
スクリプト終了時に自動的に削除されるファイルを作成し、そのパスを返します。 @param string|\SplFileInfo|null $file ファイルに書き込む文字列を格納したSplFileInfo。 @return string
[ "スクリプト終了時に自動的に削除されるファイルを作成し、そのパスを返します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/GenericDictionaryParser.php#L160-L172
esperecyan/dictionary-php
src/parser/GenericDictionaryParser.php
GenericDictionaryParser.generateTempDirectory
public function generateTempDirectory(): string { $path = sys_get_temp_dir() . '/' . self::TEMP_FILE_OR_DIRECTORY_PREFIX . bin2hex(random_bytes(self::TEMP_DIRECTORY_NAME_LENGTH)); mkdir($path); register_shutdown_function(function () use ($path) { if (!file_exists($path)) { return; } foreach (new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST ) as $file) { if ($file->isDir()) { rmdir($file->getPathname()); } else { unlink($file->getPathname()); } } rmdir($path); }); return $path; }
php
public function generateTempDirectory(): string { $path = sys_get_temp_dir() . '/' . self::TEMP_FILE_OR_DIRECTORY_PREFIX . bin2hex(random_bytes(self::TEMP_DIRECTORY_NAME_LENGTH)); mkdir($path); register_shutdown_function(function () use ($path) { if (!file_exists($path)) { return; } foreach (new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST ) as $file) { if ($file->isDir()) { rmdir($file->getPathname()); } else { unlink($file->getPathname()); } } rmdir($path); }); return $path; }
[ "public", "function", "generateTempDirectory", "(", ")", ":", "string", "{", "$", "path", "=", "sys_get_temp_dir", "(", ")", ".", "'/'", ".", "self", "::", "TEMP_FILE_OR_DIRECTORY_PREFIX", ".", "bin2hex", "(", "random_bytes", "(", "self", "::", "TEMP_DIRECTORY_NAME_LENGTH", ")", ")", ";", "mkdir", "(", "$", "path", ")", ";", "register_shutdown_function", "(", "function", "(", ")", "use", "(", "$", "path", ")", "{", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "return", ";", "}", "foreach", "(", "new", "\\", "RecursiveIteratorIterator", "(", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "path", ",", "\\", "FilesystemIterator", "::", "SKIP_DOTS", ")", ",", "\\", "RecursiveIteratorIterator", "::", "CHILD_FIRST", ")", "as", "$", "file", ")", "{", "if", "(", "$", "file", "->", "isDir", "(", ")", ")", "{", "rmdir", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "}", "else", "{", "unlink", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "}", "}", "rmdir", "(", "$", "path", ")", ";", "}", ")", ";", "return", "$", "path", ";", "}" ]
スクリプト終了時に自動的に削除されるディレクトリを作成し、そのパスを返します。 @return string
[ "スクリプト終了時に自動的に削除されるディレクトリを作成し、そのパスを返します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/GenericDictionaryParser.php#L178-L204
esperecyan/dictionary-php
src/parser/GenericDictionaryParser.php
GenericDictionaryParser.parseCSVFile
protected function parseCSVFile(Dictionary $dictionary, \SplFileInfo $csv, bool $header = null) { if (!($csv instanceof \SplFileObject)) { $csv = $csv->openFile(); } $binary = $this->correctEncoding((new Parser())->getBinary($csv)); $csv->ftruncate(0); $csv->fwrite($binary); $csv->setFlags(\SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_CSV); if ($this->isWindows()) { $previousLocale = setlocale(LC_CTYPE, '0'); setlocale(LC_CTYPE, '.1252'); } try { $first = true; foreach ($csv as $i => $fields) { if (is_null($fields[0])) { throw new SyntaxException(_('汎用辞書はCSVファイルかZIPファイルでなければなりません。') . _('壊れたCSVファイル (ダブルクォートでエスケープされていないダブルクォートを含む等) の可能性があります。')); } // 改行をLFに統一し、水平タブと改行以外のC0制御文字を取り除く foreach ($fields as &$field) { $field = preg_replace( '/[\\x00-\\x08\\x11\\x7F]+/u', '', strtr($field, ["\r\n" => "\n", "\r" => "\n", "\n" => "\n"]) ); } if ($i === 0) { if (is_null($header)) { $header = in_array('text', $fields); } if ($header) { $fieldNames = array_map(function (string $fieldName): string { return str_replace("\t", '', $fieldName); }, $fields); continue; } } $this->addRecord( $dictionary, $fieldNames ?? array_merge(['text'], array_fill(0, count($fields), 'answer')), $fields, $first ); $first = false; } } catch (\Throwable $e) { if (isset($previousLocale)) { setlocale(LC_CTYPE, $previousLocale); } throw $e; } if (isset($previousLocale)) { setlocale(LC_CTYPE, $previousLocale); } }
php
protected function parseCSVFile(Dictionary $dictionary, \SplFileInfo $csv, bool $header = null) { if (!($csv instanceof \SplFileObject)) { $csv = $csv->openFile(); } $binary = $this->correctEncoding((new Parser())->getBinary($csv)); $csv->ftruncate(0); $csv->fwrite($binary); $csv->setFlags(\SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_CSV); if ($this->isWindows()) { $previousLocale = setlocale(LC_CTYPE, '0'); setlocale(LC_CTYPE, '.1252'); } try { $first = true; foreach ($csv as $i => $fields) { if (is_null($fields[0])) { throw new SyntaxException(_('汎用辞書はCSVファイルかZIPファイルでなければなりません。') . _('壊れたCSVファイル (ダブルクォートでエスケープされていないダブルクォートを含む等) の可能性があります。')); } // 改行をLFに統一し、水平タブと改行以外のC0制御文字を取り除く foreach ($fields as &$field) { $field = preg_replace( '/[\\x00-\\x08\\x11\\x7F]+/u', '', strtr($field, ["\r\n" => "\n", "\r" => "\n", "\n" => "\n"]) ); } if ($i === 0) { if (is_null($header)) { $header = in_array('text', $fields); } if ($header) { $fieldNames = array_map(function (string $fieldName): string { return str_replace("\t", '', $fieldName); }, $fields); continue; } } $this->addRecord( $dictionary, $fieldNames ?? array_merge(['text'], array_fill(0, count($fields), 'answer')), $fields, $first ); $first = false; } } catch (\Throwable $e) { if (isset($previousLocale)) { setlocale(LC_CTYPE, $previousLocale); } throw $e; } if (isset($previousLocale)) { setlocale(LC_CTYPE, $previousLocale); } }
[ "protected", "function", "parseCSVFile", "(", "Dictionary", "$", "dictionary", ",", "\\", "SplFileInfo", "$", "csv", ",", "bool", "$", "header", "=", "null", ")", "{", "if", "(", "!", "(", "$", "csv", "instanceof", "\\", "SplFileObject", ")", ")", "{", "$", "csv", "=", "$", "csv", "->", "openFile", "(", ")", ";", "}", "$", "binary", "=", "$", "this", "->", "correctEncoding", "(", "(", "new", "Parser", "(", ")", ")", "->", "getBinary", "(", "$", "csv", ")", ")", ";", "$", "csv", "->", "ftruncate", "(", "0", ")", ";", "$", "csv", "->", "fwrite", "(", "$", "binary", ")", ";", "$", "csv", "->", "setFlags", "(", "\\", "SplFileObject", "::", "READ_AHEAD", "|", "\\", "SplFileObject", "::", "SKIP_EMPTY", "|", "\\", "SplFileObject", "::", "READ_CSV", ")", ";", "if", "(", "$", "this", "->", "isWindows", "(", ")", ")", "{", "$", "previousLocale", "=", "setlocale", "(", "LC_CTYPE", ",", "'0'", ")", ";", "setlocale", "(", "LC_CTYPE", ",", "'.1252'", ")", ";", "}", "try", "{", "$", "first", "=", "true", ";", "foreach", "(", "$", "csv", "as", "$", "i", "=>", "$", "fields", ")", "{", "if", "(", "is_null", "(", "$", "fields", "[", "0", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'汎用辞書はCSVファイルかZIPファイルでなければなりません。')", "", ".", "_", "(", "'壊れたCSVファイル (ダブルクォートでエスケープされていないダブルクォートを含む等) の可能性があります。'));", "", "", "", "}", "// 改行をLFに統一し、水平タブと改行以外のC0制御文字を取り除く", "foreach", "(", "$", "fields", "as", "&", "$", "field", ")", "{", "$", "field", "=", "preg_replace", "(", "'/[\\\\x00-\\\\x08\\\\x11\\\\x7F]+/u'", ",", "''", ",", "strtr", "(", "$", "field", ",", "[", "\"\\r\\n\"", "=>", "\"\\n\"", ",", "\"\\r\"", "=>", "\"\\n\"", ",", "\"\\n\"", "=>", "\"\\n\"", "]", ")", ")", ";", "}", "if", "(", "$", "i", "===", "0", ")", "{", "if", "(", "is_null", "(", "$", "header", ")", ")", "{", "$", "header", "=", "in_array", "(", "'text'", ",", "$", "fields", ")", ";", "}", "if", "(", "$", "header", ")", "{", "$", "fieldNames", "=", "array_map", "(", "function", "(", "string", "$", "fieldName", ")", ":", "string", "{", "return", "str_replace", "(", "\"\\t\"", ",", "''", ",", "$", "fieldName", ")", ";", "}", ",", "$", "fields", ")", ";", "continue", ";", "}", "}", "$", "this", "->", "addRecord", "(", "$", "dictionary", ",", "$", "fieldNames", "??", "array_merge", "(", "[", "'text'", "]", ",", "array_fill", "(", "0", ",", "count", "(", "$", "fields", ")", ",", "'answer'", ")", ")", ",", "$", "fields", ",", "$", "first", ")", ";", "$", "first", "=", "false", ";", "}", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "if", "(", "isset", "(", "$", "previousLocale", ")", ")", "{", "setlocale", "(", "LC_CTYPE", ",", "$", "previousLocale", ")", ";", "}", "throw", "$", "e", ";", "}", "if", "(", "isset", "(", "$", "previousLocale", ")", ")", "{", "setlocale", "(", "LC_CTYPE", ",", "$", "previousLocale", ")", ";", "}", "}" ]
CSVファイルからお題を取得し、Dictionaryクラスに追加します。 @param Dictionary $dictionary @param \SplFileInfo $csv @param bool|null $header @throws SyntaxException CSVファイルが壊れている場合。
[ "CSVファイルからお題を取得し、Dictionaryクラスに追加します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/GenericDictionaryParser.php#L222-L285
esperecyan/dictionary-php
src/parser/GenericDictionaryParser.php
GenericDictionaryParser.parseArchive
protected function parseArchive(\SplFileInfo $file): \SplFileInfo { $archive = new \ZipArchive(); $result = $archive->open( $file instanceof \SplTempFileObject ? $this->generateTempFile($file) : $file->getRealPath(), \ZipArchive::CHECKCONS ); if ($result !== true) { switch ($result) { case \ZipArchive::ER_INCONS: case \ZipArchive::ER_NOZIP: throw new SyntaxException(_('妥当なZIPファイルではありません。')); default: throw new \LogicException("ZIPファイルの解析に失敗しました。エラーコード: $result"); } } $tempDirectoryPath = $this->generateTempDirectory(); $archive->extractTo($tempDirectoryPath); $archive->close(); $files = new \FilesystemIterator($tempDirectoryPath, \FilesystemIterator::KEY_AS_FILENAME); $finfo = new Finfo(FILEINFO_MIME_TYPE); $validator = new \esperecyan\dictionary_php\Validator(); $validator->setLogger($this->logger); foreach ($files as $filename => $file) { if ($filename === 'dictionary.csv') { if (!in_array($finfo->file($file), ['text/plain', 'text/csv'])) { throw new SyntaxException(_('「dictionary.csv」は通常のテキストファイルとして認識できません。')); } $csvFile = $file; continue; } $validator->correct($file, $filename); } if (empty($csvFile)) { throw new SyntaxException(_('「dictionary.csv」が見つかりません。')); } return $csvFile; }
php
protected function parseArchive(\SplFileInfo $file): \SplFileInfo { $archive = new \ZipArchive(); $result = $archive->open( $file instanceof \SplTempFileObject ? $this->generateTempFile($file) : $file->getRealPath(), \ZipArchive::CHECKCONS ); if ($result !== true) { switch ($result) { case \ZipArchive::ER_INCONS: case \ZipArchive::ER_NOZIP: throw new SyntaxException(_('妥当なZIPファイルではありません。')); default: throw new \LogicException("ZIPファイルの解析に失敗しました。エラーコード: $result"); } } $tempDirectoryPath = $this->generateTempDirectory(); $archive->extractTo($tempDirectoryPath); $archive->close(); $files = new \FilesystemIterator($tempDirectoryPath, \FilesystemIterator::KEY_AS_FILENAME); $finfo = new Finfo(FILEINFO_MIME_TYPE); $validator = new \esperecyan\dictionary_php\Validator(); $validator->setLogger($this->logger); foreach ($files as $filename => $file) { if ($filename === 'dictionary.csv') { if (!in_array($finfo->file($file), ['text/plain', 'text/csv'])) { throw new SyntaxException(_('「dictionary.csv」は通常のテキストファイルとして認識できません。')); } $csvFile = $file; continue; } $validator->correct($file, $filename); } if (empty($csvFile)) { throw new SyntaxException(_('「dictionary.csv」が見つかりません。')); } return $csvFile; }
[ "protected", "function", "parseArchive", "(", "\\", "SplFileInfo", "$", "file", ")", ":", "\\", "SplFileInfo", "{", "$", "archive", "=", "new", "\\", "ZipArchive", "(", ")", ";", "$", "result", "=", "$", "archive", "->", "open", "(", "$", "file", "instanceof", "\\", "SplTempFileObject", "?", "$", "this", "->", "generateTempFile", "(", "$", "file", ")", ":", "$", "file", "->", "getRealPath", "(", ")", ",", "\\", "ZipArchive", "::", "CHECKCONS", ")", ";", "if", "(", "$", "result", "!==", "true", ")", "{", "switch", "(", "$", "result", ")", "{", "case", "\\", "ZipArchive", "::", "ER_INCONS", ":", "case", "\\", "ZipArchive", "::", "ER_NOZIP", ":", "throw", "new", "SyntaxException", "(", "_", "(", "'妥当なZIPファイルではありません。'));", "", "", "", "default", ":", "throw", "new", "\\", "LogicException", "(", "\"ZIPファイルの解析に失敗しました。エラーコード: $result\");", "", "", "}", "}", "$", "tempDirectoryPath", "=", "$", "this", "->", "generateTempDirectory", "(", ")", ";", "$", "archive", "->", "extractTo", "(", "$", "tempDirectoryPath", ")", ";", "$", "archive", "->", "close", "(", ")", ";", "$", "files", "=", "new", "\\", "FilesystemIterator", "(", "$", "tempDirectoryPath", ",", "\\", "FilesystemIterator", "::", "KEY_AS_FILENAME", ")", ";", "$", "finfo", "=", "new", "Finfo", "(", "FILEINFO_MIME_TYPE", ")", ";", "$", "validator", "=", "new", "\\", "esperecyan", "\\", "dictionary_php", "\\", "Validator", "(", ")", ";", "$", "validator", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "foreach", "(", "$", "files", "as", "$", "filename", "=>", "$", "file", ")", "{", "if", "(", "$", "filename", "===", "'dictionary.csv'", ")", "{", "if", "(", "!", "in_array", "(", "$", "finfo", "->", "file", "(", "$", "file", ")", ",", "[", "'text/plain'", ",", "'text/csv'", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'「dictionary.csv」は通常のテキストファイルとして認識できません。'));", "", "", "", "}", "$", "csvFile", "=", "$", "file", ";", "continue", ";", "}", "$", "validator", "->", "correct", "(", "$", "file", ",", "$", "filename", ")", ";", "}", "if", "(", "empty", "(", "$", "csvFile", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'「dictionary.csv」が見つかりません。'));", "", "", "", "}", "return", "$", "csvFile", ";", "}" ]
ZIPアーカイブを解析し、ファイルの矯正を行います。 @param SplFileInfo $file @throws SyntaxException @throws \LogicException 権限エラーなどでZIPファイルを開けなかった場合、または書き込めなかった場合。 @return \SplFileObject CSVファイル。
[ "ZIPアーカイブを解析し、ファイルの矯正を行います。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/GenericDictionaryParser.php#L294-L336
opis/utils
lib/Mutex.php
Mutex.lock
public function lock() { if ($this->fp === null) { $this->fp = fopen($this->file, 'r'); } return flock($this->fp, LOCK_EX); }
php
public function lock() { if ($this->fp === null) { $this->fp = fopen($this->file, 'r'); } return flock($this->fp, LOCK_EX); }
[ "public", "function", "lock", "(", ")", "{", "if", "(", "$", "this", "->", "fp", "===", "null", ")", "{", "$", "this", "->", "fp", "=", "fopen", "(", "$", "this", "->", "file", ",", "'r'", ")", ";", "}", "return", "flock", "(", "$", "this", "->", "fp", ",", "LOCK_EX", ")", ";", "}" ]
Aquire the mutex @return boolean
[ "Aquire", "the", "mutex" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/Mutex.php#L73-L80
opis/utils
lib/Mutex.php
Mutex.unlock
public function unlock() { if ($this->fp !== null) { flock($this->fp, LOCK_UN); fclose($this->fp); $this->fp = null; } return true; }
php
public function unlock() { if ($this->fp !== null) { flock($this->fp, LOCK_UN); fclose($this->fp); $this->fp = null; } return true; }
[ "public", "function", "unlock", "(", ")", "{", "if", "(", "$", "this", "->", "fp", "!==", "null", ")", "{", "flock", "(", "$", "this", "->", "fp", ",", "LOCK_UN", ")", ";", "fclose", "(", "$", "this", "->", "fp", ")", ";", "$", "this", "->", "fp", "=", "null", ";", "}", "return", "true", ";", "}" ]
Realese the mutex @return boolean
[ "Realese", "the", "mutex" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/Mutex.php#L87-L96
harp-orm/query
src/Compiler/Update.php
Update.render
public static function render(Query\Update $query) { return Compiler::withDb($query->getDb(), function () use ($query) { return Compiler::expression(array( 'UPDATE', $query->getType(), Aliased::combine($query->getTable()), Join::combine($query->getJoin()), Compiler::word('SET', Set::combine($query->getSet())), Compiler::word('WHERE', Condition::combine($query->getWhere())), Compiler::word('ORDER BY', Direction::combine($query->getOrder())), Compiler::word('LIMIT', $query->getLimit()), )); }); }
php
public static function render(Query\Update $query) { return Compiler::withDb($query->getDb(), function () use ($query) { return Compiler::expression(array( 'UPDATE', $query->getType(), Aliased::combine($query->getTable()), Join::combine($query->getJoin()), Compiler::word('SET', Set::combine($query->getSet())), Compiler::word('WHERE', Condition::combine($query->getWhere())), Compiler::word('ORDER BY', Direction::combine($query->getOrder())), Compiler::word('LIMIT', $query->getLimit()), )); }); }
[ "public", "static", "function", "render", "(", "Query", "\\", "Update", "$", "query", ")", "{", "return", "Compiler", "::", "withDb", "(", "$", "query", "->", "getDb", "(", ")", ",", "function", "(", ")", "use", "(", "$", "query", ")", "{", "return", "Compiler", "::", "expression", "(", "array", "(", "'UPDATE'", ",", "$", "query", "->", "getType", "(", ")", ",", "Aliased", "::", "combine", "(", "$", "query", "->", "getTable", "(", ")", ")", ",", "Join", "::", "combine", "(", "$", "query", "->", "getJoin", "(", ")", ")", ",", "Compiler", "::", "word", "(", "'SET'", ",", "Set", "::", "combine", "(", "$", "query", "->", "getSet", "(", ")", ")", ")", ",", "Compiler", "::", "word", "(", "'WHERE'", ",", "Condition", "::", "combine", "(", "$", "query", "->", "getWhere", "(", ")", ")", ")", ",", "Compiler", "::", "word", "(", "'ORDER BY'", ",", "Direction", "::", "combine", "(", "$", "query", "->", "getOrder", "(", ")", ")", ")", ",", "Compiler", "::", "word", "(", "'LIMIT'", ",", "$", "query", "->", "getLimit", "(", ")", ")", ",", ")", ")", ";", "}", ")", ";", "}" ]
Render Update object @param Query\Update $query @return string
[ "Render", "Update", "object" ]
train
https://github.com/harp-orm/query/blob/98ce2468a0a31fe15ed3692bad32547bf6dbe41a/src/Compiler/Update.php#L19-L33
tonicospinelli/class-generation
src/ClassGeneration/UseCollection.php
UseCollection.toString
public function toString() { $uses = $this->getIterator(); $string = ''; foreach ($uses as $use) { $string .= $use->toString(); } return $string; }
php
public function toString() { $uses = $this->getIterator(); $string = ''; foreach ($uses as $use) { $string .= $use->toString(); } return $string; }
[ "public", "function", "toString", "(", ")", "{", "$", "uses", "=", "$", "this", "->", "getIterator", "(", ")", ";", "$", "string", "=", "''", ";", "foreach", "(", "$", "uses", "as", "$", "use", ")", "{", "$", "string", ".=", "$", "use", "->", "toString", "(", ")", ";", "}", "return", "$", "string", ";", "}" ]
Parse the Uses to string; @return string
[ "Parse", "the", "Uses", "to", "string", ";" ]
train
https://github.com/tonicospinelli/class-generation/blob/eee63bdb68c066b25b885b57b23656e809381a76/src/ClassGeneration/UseCollection.php#L67-L76
harp-orm/query
src/Compiler/Values.php
Values.render
public static function render(SQL\Values $item) { $placeholders = array_fill(0, count($item->getParameters()), '?'); return '('.join(', ', $placeholders).')'; }
php
public static function render(SQL\Values $item) { $placeholders = array_fill(0, count($item->getParameters()), '?'); return '('.join(', ', $placeholders).')'; }
[ "public", "static", "function", "render", "(", "SQL", "\\", "Values", "$", "item", ")", "{", "$", "placeholders", "=", "array_fill", "(", "0", ",", "count", "(", "$", "item", "->", "getParameters", "(", ")", ")", ",", "'?'", ")", ";", "return", "'('", ".", "join", "(", "', '", ",", "$", "placeholders", ")", ".", "')'", ";", "}" ]
Render Values object @param SQL\Values $item @return string
[ "Render", "Values", "object" ]
train
https://github.com/harp-orm/query/blob/98ce2468a0a31fe15ed3692bad32547bf6dbe41a/src/Compiler/Values.php#L30-L35
movoin/one-swoole
src/Protocol/Traits/HasMessage.php
HasMessage.withProtocol
public function withProtocol(string $protocol): self { if ($this->protocol === $protocol) { return $this; } $clone = clone $this; $clone->protocol = $protocol; return $clone; }
php
public function withProtocol(string $protocol): self { if ($this->protocol === $protocol) { return $this; } $clone = clone $this; $clone->protocol = $protocol; return $clone; }
[ "public", "function", "withProtocol", "(", "string", "$", "protocol", ")", ":", "self", "{", "if", "(", "$", "this", "->", "protocol", "===", "$", "protocol", ")", "{", "return", "$", "this", ";", "}", "$", "clone", "=", "clone", "$", "this", ";", "$", "clone", "->", "protocol", "=", "$", "protocol", ";", "return", "$", "clone", ";", "}" ]
设置协议 @param string $protocol @return self
[ "设置协议" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Traits/HasMessage.php#L86-L96
movoin/one-swoole
src/Protocol/Traits/HasMessage.php
HasMessage.withHeader
public function withHeader($name, $value): self { $this->assertHeaderName($name); $clone = clone $this; $clone->headers->set($name, $value); return $clone; }
php
public function withHeader($name, $value): self { $this->assertHeaderName($name); $clone = clone $this; $clone->headers->set($name, $value); return $clone; }
[ "public", "function", "withHeader", "(", "$", "name", ",", "$", "value", ")", ":", "self", "{", "$", "this", "->", "assertHeaderName", "(", "$", "name", ")", ";", "$", "clone", "=", "clone", "$", "this", ";", "$", "clone", "->", "headers", "->", "set", "(", "$", "name", ",", "$", "value", ")", ";", "return", "$", "clone", ";", "}" ]
获得指定头信息的消息对象 @param string $name @param mixed $value @return self @throws \InvalidArgumentException
[ "获得指定头信息的消息对象" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Traits/HasMessage.php#L186-L194
movoin/one-swoole
src/Protocol/Traits/HasMessage.php
HasMessage.withAddedHeader
public function withAddedHeader($name, $value): self { $this->assertHeaderName($name); $clone = clone $this; $clone->headers->add($name, $value); return $clone; }
php
public function withAddedHeader($name, $value): self { $this->assertHeaderName($name); $clone = clone $this; $clone->headers->add($name, $value); return $clone; }
[ "public", "function", "withAddedHeader", "(", "$", "name", ",", "$", "value", ")", ":", "self", "{", "$", "this", "->", "assertHeaderName", "(", "$", "name", ")", ";", "$", "clone", "=", "clone", "$", "this", ";", "$", "clone", "->", "headers", "->", "add", "(", "$", "name", ",", "$", "value", ")", ";", "return", "$", "clone", ";", "}" ]
获得添加具体头信息的消息对象 @param string $name @param mixed $value @return self @throws \InvalidArgumentException
[ "获得添加具体头信息的消息对象" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Traits/HasMessage.php#L205-L213
movoin/one-swoole
src/Protocol/Traits/HasMessage.php
HasMessage.withoutHeader
public function withoutHeader($name): self { $this->assertHeaderName($name); $clone = clone $this; $clone->headers->remove($name); return $clone; }
php
public function withoutHeader($name): self { $this->assertHeaderName($name); $clone = clone $this; $clone->headers->remove($name); return $clone; }
[ "public", "function", "withoutHeader", "(", "$", "name", ")", ":", "self", "{", "$", "this", "->", "assertHeaderName", "(", "$", "name", ")", ";", "$", "clone", "=", "clone", "$", "this", ";", "$", "clone", "->", "headers", "->", "remove", "(", "$", "name", ")", ";", "return", "$", "clone", ";", "}" ]
获得移除具体头信息的消息对象 @param string $name @return self @throws \InvalidArgumentException
[ "获得移除具体头信息的消息对象" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Traits/HasMessage.php#L223-L231
movoin/one-swoole
src/Protocol/Traits/HasMessage.php
HasMessage.getBody
public function getBody(): StreamInterface { if ($this->body->eof()) { $this->body->rewind(); } return $this->body; }
php
public function getBody(): StreamInterface { if ($this->body->eof()) { $this->body->rewind(); } return $this->body; }
[ "public", "function", "getBody", "(", ")", ":", "StreamInterface", "{", "if", "(", "$", "this", "->", "body", "->", "eof", "(", ")", ")", "{", "$", "this", "->", "body", "->", "rewind", "(", ")", ";", "}", "return", "$", "this", "->", "body", ";", "}" ]
获得消息正文 @return \Psr\Http\Message\StreamInterface
[ "获得消息正文" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Traits/HasMessage.php#L238-L245
activecollab/databasestructure
src/Field/Composite/NameField.php
NameField.onAddedToType
public function onAddedToType(TypeInterface &$type) { parent::onAddedToType($type); $type->serialize($this->getName()); }
php
public function onAddedToType(TypeInterface &$type) { parent::onAddedToType($type); $type->serialize($this->getName()); }
[ "public", "function", "onAddedToType", "(", "TypeInterface", "&", "$", "type", ")", "{", "parent", "::", "onAddedToType", "(", "$", "type", ")", ";", "$", "type", "->", "serialize", "(", "$", "this", "->", "getName", "(", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Field/Composite/NameField.php#L33-L38
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.addBindingType
public function addBindingType(BindingType $type) { if (null === $this->json) { $this->load(); } if (isset($this->json['keysByTypeName'][$type->getName()])) { throw DuplicateTypeException::forTypeName($type->getName()); } $key = $this->json['nextKey']++; $this->json['keysByTypeName'][$type->getName()] = $key; $this->typesByKey[$key] = $type; // Use integer keys to reduce storage space // (compared to fully-qualified class names) $this->json['typesByKey'][$key] = serialize($type); $this->flush(); }
php
public function addBindingType(BindingType $type) { if (null === $this->json) { $this->load(); } if (isset($this->json['keysByTypeName'][$type->getName()])) { throw DuplicateTypeException::forTypeName($type->getName()); } $key = $this->json['nextKey']++; $this->json['keysByTypeName'][$type->getName()] = $key; $this->typesByKey[$key] = $type; // Use integer keys to reduce storage space // (compared to fully-qualified class names) $this->json['typesByKey'][$key] = serialize($type); $this->flush(); }
[ "public", "function", "addBindingType", "(", "BindingType", "$", "type", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "type", "->", "getName", "(", ")", "]", ")", ")", "{", "throw", "DuplicateTypeException", "::", "forTypeName", "(", "$", "type", "->", "getName", "(", ")", ")", ";", "}", "$", "key", "=", "$", "this", "->", "json", "[", "'nextKey'", "]", "++", ";", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "type", "->", "getName", "(", ")", "]", "=", "$", "key", ";", "$", "this", "->", "typesByKey", "[", "$", "key", "]", "=", "$", "type", ";", "// Use integer keys to reduce storage space", "// (compared to fully-qualified class names)", "$", "this", "->", "json", "[", "'typesByKey'", "]", "[", "$", "key", "]", "=", "serialize", "(", "$", "type", ")", ";", "$", "this", "->", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L90-L111
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.removeBindingType
public function removeBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return; } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->bindingsByKey[$key])) { // no initialize, since we're removing this anyway $this->loadBindingsForKey($key, false); } unset($this->typesByKey[$key]); unset($this->bindingsByKey[$key]); unset($this->json['keysByTypeName'][$typeName]); unset($this->json['typesByKey'][$key]); unset($this->json['bindingsByKey'][$key]); $this->flush(); }
php
public function removeBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return; } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->bindingsByKey[$key])) { // no initialize, since we're removing this anyway $this->loadBindingsForKey($key, false); } unset($this->typesByKey[$key]); unset($this->bindingsByKey[$key]); unset($this->json['keysByTypeName'][$typeName]); unset($this->json['typesByKey'][$key]); unset($this->json['bindingsByKey'][$key]); $this->flush(); }
[ "public", "function", "removeBindingType", "(", "$", "typeName", ")", "{", "Assert", "::", "stringNotEmpty", "(", "$", "typeName", ",", "'The type class must be a non-empty string. Got: %s'", ")", ";", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ")", "{", "return", ";", "}", "$", "key", "=", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ")", "{", "// no initialize, since we're removing this anyway", "$", "this", "->", "loadBindingsForKey", "(", "$", "key", ",", "false", ")", ";", "}", "unset", "(", "$", "this", "->", "typesByKey", "[", "$", "key", "]", ")", ";", "unset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ";", "unset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ";", "unset", "(", "$", "this", "->", "json", "[", "'typesByKey'", "]", "[", "$", "key", "]", ")", ";", "unset", "(", "$", "this", "->", "json", "[", "'bindingsByKey'", "]", "[", "$", "key", "]", ")", ";", "$", "this", "->", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L116-L143
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.removeBindingTypes
public function removeBindingTypes() { if (null === $this->json) { $this->load(); } $this->typesByKey = array(); $this->bindingsByKey = array(); $this->json['keysByTypeName'] = array(); $this->json['typesByKey'] = array(); $this->json['bindingsByKey'] = array(); $this->json['nextKey'] = 0; $this->flush(); }
php
public function removeBindingTypes() { if (null === $this->json) { $this->load(); } $this->typesByKey = array(); $this->bindingsByKey = array(); $this->json['keysByTypeName'] = array(); $this->json['typesByKey'] = array(); $this->json['bindingsByKey'] = array(); $this->json['nextKey'] = 0; $this->flush(); }
[ "public", "function", "removeBindingTypes", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "$", "this", "->", "typesByKey", "=", "array", "(", ")", ";", "$", "this", "->", "bindingsByKey", "=", "array", "(", ")", ";", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "=", "array", "(", ")", ";", "$", "this", "->", "json", "[", "'typesByKey'", "]", "=", "array", "(", ")", ";", "$", "this", "->", "json", "[", "'bindingsByKey'", "]", "=", "array", "(", ")", ";", "$", "this", "->", "json", "[", "'nextKey'", "]", "=", "0", ";", "$", "this", "->", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L148-L163
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.hasBindingType
public function hasBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (null === $this->json) { $this->load(); } return isset($this->json['keysByTypeName'][$typeName]); }
php
public function hasBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (null === $this->json) { $this->load(); } return isset($this->json['keysByTypeName'][$typeName]); }
[ "public", "function", "hasBindingType", "(", "$", "typeName", ")", "{", "Assert", "::", "stringNotEmpty", "(", "$", "typeName", ",", "'The type class must be a non-empty string. Got: %s'", ")", ";", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "return", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L168-L177
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.getBindingType
public function getBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { throw NoSuchTypeException::forTypeName($typeName); } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->typesByKey[$key])) { $this->typesByKey[$key] = unserialize($this->json['typesByKey'][$key]); } return $this->typesByKey[$key]; }
php
public function getBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { throw NoSuchTypeException::forTypeName($typeName); } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->typesByKey[$key])) { $this->typesByKey[$key] = unserialize($this->json['typesByKey'][$key]); } return $this->typesByKey[$key]; }
[ "public", "function", "getBindingType", "(", "$", "typeName", ")", "{", "Assert", "::", "stringNotEmpty", "(", "$", "typeName", ",", "'The type class must be a non-empty string. Got: %s'", ")", ";", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ")", "{", "throw", "NoSuchTypeException", "::", "forTypeName", "(", "$", "typeName", ")", ";", "}", "$", "key", "=", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "typesByKey", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "typesByKey", "[", "$", "key", "]", "=", "unserialize", "(", "$", "this", "->", "json", "[", "'typesByKey'", "]", "[", "$", "key", "]", ")", ";", "}", "return", "$", "this", "->", "typesByKey", "[", "$", "key", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L182-L201
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.getBindingTypes
public function getBindingTypes() { if (null === $this->json) { $this->load(); } foreach ($this->json['keysByTypeName'] as $key) { if (!isset($this->typesByKey[$key])) { $this->typesByKey[$key] = unserialize($this->json['typesByKey'][$key]); } } ksort($this->typesByKey); return $this->typesByKey; }
php
public function getBindingTypes() { if (null === $this->json) { $this->load(); } foreach ($this->json['keysByTypeName'] as $key) { if (!isset($this->typesByKey[$key])) { $this->typesByKey[$key] = unserialize($this->json['typesByKey'][$key]); } } ksort($this->typesByKey); return $this->typesByKey; }
[ "public", "function", "getBindingTypes", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "foreach", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "as", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "typesByKey", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "typesByKey", "[", "$", "key", "]", "=", "unserialize", "(", "$", "this", "->", "json", "[", "'typesByKey'", "]", "[", "$", "key", "]", ")", ";", "}", "}", "ksort", "(", "$", "this", "->", "typesByKey", ")", ";", "return", "$", "this", "->", "typesByKey", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L218-L233
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.addBinding
public function addBinding(Binding $binding) { if (null === $this->json) { $this->load(); } $typeName = $binding->getTypeName(); if (!isset($this->json['keysByTypeName'][$typeName])) { throw NoSuchTypeException::forTypeName($typeName); } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } $this->initializeBinding($binding); $this->bindingsByKey[$key][] = $binding; $this->json['bindingsByKey'][$key] = serialize($this->bindingsByKey[$key]); $this->flush(); }
php
public function addBinding(Binding $binding) { if (null === $this->json) { $this->load(); } $typeName = $binding->getTypeName(); if (!isset($this->json['keysByTypeName'][$typeName])) { throw NoSuchTypeException::forTypeName($typeName); } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } $this->initializeBinding($binding); $this->bindingsByKey[$key][] = $binding; $this->json['bindingsByKey'][$key] = serialize($this->bindingsByKey[$key]); $this->flush(); }
[ "public", "function", "addBinding", "(", "Binding", "$", "binding", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "$", "typeName", "=", "$", "binding", "->", "getTypeName", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ")", "{", "throw", "NoSuchTypeException", "::", "forTypeName", "(", "$", "typeName", ")", ";", "}", "$", "key", "=", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "loadBindingsForKey", "(", "$", "key", ")", ";", "}", "$", "this", "->", "initializeBinding", "(", "$", "binding", ")", ";", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", "[", "]", "=", "$", "binding", ";", "$", "this", "->", "json", "[", "'bindingsByKey'", "]", "[", "$", "key", "]", "=", "serialize", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ";", "$", "this", "->", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L238-L263
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.findBindings
public function findBindings($typeName, Expression $expr = null) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return array(); } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } $bindings = $this->bindingsByKey[$key]; if (null !== $expr) { $bindings = Expr::filter($bindings, $expr); } return $bindings; }
php
public function findBindings($typeName, Expression $expr = null) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return array(); } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } $bindings = $this->bindingsByKey[$key]; if (null !== $expr) { $bindings = Expr::filter($bindings, $expr); } return $bindings; }
[ "public", "function", "findBindings", "(", "$", "typeName", ",", "Expression", "$", "expr", "=", "null", ")", "{", "Assert", "::", "stringNotEmpty", "(", "$", "typeName", ",", "'The type class must be a non-empty string. Got: %s'", ")", ";", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ")", "{", "return", "array", "(", ")", ";", "}", "$", "key", "=", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "loadBindingsForKey", "(", "$", "key", ")", ";", "}", "$", "bindings", "=", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ";", "if", "(", "null", "!==", "$", "expr", ")", "{", "$", "bindings", "=", "Expr", "::", "filter", "(", "$", "bindings", ",", "$", "expr", ")", ";", "}", "return", "$", "bindings", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L268-L293
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.getBindings
public function getBindings() { if (null === $this->json) { $this->load(); } $this->loadAllBindings(); $bindings = array(); foreach ($this->bindingsByKey as $bindingsForKey) { $bindings = array_merge($bindings, $bindingsForKey); } return $bindings; }
php
public function getBindings() { if (null === $this->json) { $this->load(); } $this->loadAllBindings(); $bindings = array(); foreach ($this->bindingsByKey as $bindingsForKey) { $bindings = array_merge($bindings, $bindingsForKey); } return $bindings; }
[ "public", "function", "getBindings", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "$", "this", "->", "loadAllBindings", "(", ")", ";", "$", "bindings", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "bindingsByKey", "as", "$", "bindingsForKey", ")", "{", "$", "bindings", "=", "array_merge", "(", "$", "bindings", ",", "$", "bindingsForKey", ")", ";", "}", "return", "$", "bindings", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L298-L313
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.removeAllBindings
protected function removeAllBindings() { if (null === $this->json) { $this->load(); } $this->bindingsByKey = array(); $this->json['bindingsByKey'] = array(); $this->flush(); }
php
protected function removeAllBindings() { if (null === $this->json) { $this->load(); } $this->bindingsByKey = array(); $this->json['bindingsByKey'] = array(); $this->flush(); }
[ "protected", "function", "removeAllBindings", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "$", "this", "->", "bindingsByKey", "=", "array", "(", ")", ";", "$", "this", "->", "json", "[", "'bindingsByKey'", "]", "=", "array", "(", ")", ";", "$", "this", "->", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L318-L329
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.removeBindingsThatMatch
protected function removeBindingsThatMatch(Expression $expr) { if (null === $this->json) { $this->load(); } $this->loadAllBindings(); foreach ($this->bindingsByKey as $key => $bindingsForKey) { foreach ($bindingsForKey as $i => $binding) { if ($expr->evaluate($binding)) { unset($this->bindingsByKey[$key][$i]); } } $this->reindexBindingsForKey($key); $this->syncBindingsForKey($key); } $this->flush(); }
php
protected function removeBindingsThatMatch(Expression $expr) { if (null === $this->json) { $this->load(); } $this->loadAllBindings(); foreach ($this->bindingsByKey as $key => $bindingsForKey) { foreach ($bindingsForKey as $i => $binding) { if ($expr->evaluate($binding)) { unset($this->bindingsByKey[$key][$i]); } } $this->reindexBindingsForKey($key); $this->syncBindingsForKey($key); } $this->flush(); }
[ "protected", "function", "removeBindingsThatMatch", "(", "Expression", "$", "expr", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "$", "this", "->", "loadAllBindings", "(", ")", ";", "foreach", "(", "$", "this", "->", "bindingsByKey", "as", "$", "key", "=>", "$", "bindingsForKey", ")", "{", "foreach", "(", "$", "bindingsForKey", "as", "$", "i", "=>", "$", "binding", ")", "{", "if", "(", "$", "expr", "->", "evaluate", "(", "$", "binding", ")", ")", "{", "unset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", "[", "$", "i", "]", ")", ";", "}", "}", "$", "this", "->", "reindexBindingsForKey", "(", "$", "key", ")", ";", "$", "this", "->", "syncBindingsForKey", "(", "$", "key", ")", ";", "}", "$", "this", "->", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L334-L354
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.removeBindingsWithTypeName
protected function removeBindingsWithTypeName($typeName) { if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return; } $key = $this->json['keysByTypeName'][$typeName]; unset( $this->bindingsByKey[$key], $this->json['bindingsByKey'][$key] ); $this->flush(); }
php
protected function removeBindingsWithTypeName($typeName) { if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return; } $key = $this->json['keysByTypeName'][$typeName]; unset( $this->bindingsByKey[$key], $this->json['bindingsByKey'][$key] ); $this->flush(); }
[ "protected", "function", "removeBindingsWithTypeName", "(", "$", "typeName", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ")", "{", "return", ";", "}", "$", "key", "=", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ";", "unset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ",", "$", "this", "->", "json", "[", "'bindingsByKey'", "]", "[", "$", "key", "]", ")", ";", "$", "this", "->", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L359-L377
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.removeBindingsWithTypeNameThatMatch
protected function removeBindingsWithTypeNameThatMatch($typeName, Expression $expr) { if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return; } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } foreach ($this->bindingsByKey[$key] as $i => $binding) { if ($expr->evaluate($binding)) { unset($this->bindingsByKey[$key][$i]); } } $this->reindexBindingsForKey($key); $this->syncBindingsForKey($key); $this->flush(); }
php
protected function removeBindingsWithTypeNameThatMatch($typeName, Expression $expr) { if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return; } $key = $this->json['keysByTypeName'][$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } foreach ($this->bindingsByKey[$key] as $i => $binding) { if ($expr->evaluate($binding)) { unset($this->bindingsByKey[$key][$i]); } } $this->reindexBindingsForKey($key); $this->syncBindingsForKey($key); $this->flush(); }
[ "protected", "function", "removeBindingsWithTypeNameThatMatch", "(", "$", "typeName", ",", "Expression", "$", "expr", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ")", "{", "return", ";", "}", "$", "key", "=", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "loadBindingsForKey", "(", "$", "key", ")", ";", "}", "foreach", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", "as", "$", "i", "=>", "$", "binding", ")", "{", "if", "(", "$", "expr", "->", "evaluate", "(", "$", "binding", ")", ")", "{", "unset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", "[", "$", "i", "]", ")", ";", "}", "}", "$", "this", "->", "reindexBindingsForKey", "(", "$", "key", ")", ";", "$", "this", "->", "syncBindingsForKey", "(", "$", "key", ")", ";", "$", "this", "->", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L382-L408
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.hasBindingsWithTypeName
protected function hasBindingsWithTypeName($typeName) { if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return false; } $key = $this->json['keysByTypeName'][$typeName]; return isset($this->json['bindingsByKey'][$key]); }
php
protected function hasBindingsWithTypeName($typeName) { if (null === $this->json) { $this->load(); } if (!isset($this->json['keysByTypeName'][$typeName])) { return false; } $key = $this->json['keysByTypeName'][$typeName]; return isset($this->json['bindingsByKey'][$key]); }
[ "protected", "function", "hasBindingsWithTypeName", "(", "$", "typeName", ")", "{", "if", "(", "null", "===", "$", "this", "->", "json", ")", "{", "$", "this", "->", "load", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ")", ")", "{", "return", "false", ";", "}", "$", "key", "=", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "[", "$", "typeName", "]", ";", "return", "isset", "(", "$", "this", "->", "json", "[", "'bindingsByKey'", "]", "[", "$", "key", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L447-L460
puli/discovery
src/JsonDiscovery.php
JsonDiscovery.load
private function load() { $decoder = new JsonDecoder(); $decoder->setObjectDecoding(JsonDecoder::ASSOC_ARRAY); $this->json = file_exists($this->path) ? $decoder->decodeFile($this->path) : array(); if (!isset($this->json['keysByTypeName'])) { $this->json['keysByTypeName'] = array(); $this->json['typesByKey'] = array(); $this->json['bindingsByKey'] = array(); $this->json['nextKey'] = 0; } }
php
private function load() { $decoder = new JsonDecoder(); $decoder->setObjectDecoding(JsonDecoder::ASSOC_ARRAY); $this->json = file_exists($this->path) ? $decoder->decodeFile($this->path) : array(); if (!isset($this->json['keysByTypeName'])) { $this->json['keysByTypeName'] = array(); $this->json['typesByKey'] = array(); $this->json['bindingsByKey'] = array(); $this->json['nextKey'] = 0; } }
[ "private", "function", "load", "(", ")", "{", "$", "decoder", "=", "new", "JsonDecoder", "(", ")", ";", "$", "decoder", "->", "setObjectDecoding", "(", "JsonDecoder", "::", "ASSOC_ARRAY", ")", ";", "$", "this", "->", "json", "=", "file_exists", "(", "$", "this", "->", "path", ")", "?", "$", "decoder", "->", "decodeFile", "(", "$", "this", "->", "path", ")", ":", "array", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", ")", ")", "{", "$", "this", "->", "json", "[", "'keysByTypeName'", "]", "=", "array", "(", ")", ";", "$", "this", "->", "json", "[", "'typesByKey'", "]", "=", "array", "(", ")", ";", "$", "this", "->", "json", "[", "'bindingsByKey'", "]", "=", "array", "(", ")", ";", "$", "this", "->", "json", "[", "'nextKey'", "]", "=", "0", ";", "}", "}" ]
Loads the JSON file.
[ "Loads", "the", "JSON", "file", "." ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/JsonDiscovery.php#L529-L544
e0ipso/drupal-unit-autoload
src/Loader.php
Loader.setClassMap
public function setClassMap(array $class_map) { // Remove the leading \ from the class names. $unprefixed_class_map = array(); foreach ($class_map as $class_name => $tokenized_path) { $unprefixed_class_map[static::unprefixClass($class_name)] = $tokenized_path; } $this->classMap = $unprefixed_class_map; }
php
public function setClassMap(array $class_map) { // Remove the leading \ from the class names. $unprefixed_class_map = array(); foreach ($class_map as $class_name => $tokenized_path) { $unprefixed_class_map[static::unprefixClass($class_name)] = $tokenized_path; } $this->classMap = $unprefixed_class_map; }
[ "public", "function", "setClassMap", "(", "array", "$", "class_map", ")", "{", "// Remove the leading \\ from the class names.", "$", "unprefixed_class_map", "=", "array", "(", ")", ";", "foreach", "(", "$", "class_map", "as", "$", "class_name", "=>", "$", "tokenized_path", ")", "{", "$", "unprefixed_class_map", "[", "static", "::", "unprefixClass", "(", "$", "class_name", ")", "]", "=", "$", "tokenized_path", ";", "}", "$", "this", "->", "classMap", "=", "$", "unprefixed_class_map", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/e0ipso/drupal-unit-autoload/blob/7ce147b269c7333eca31e2cd04b736d6274b9cbf/src/Loader.php#L73-L80
e0ipso/drupal-unit-autoload
src/Loader.php
Loader.setPsrClassMap
public function setPsrClassMap(array $class_map) { // Remove the leading \ from the partial namespaces. $unprefixed_class_map = array(); foreach ($class_map as $psr => $psr_class_map) { $unprefixed_class_map[$psr] = array(); foreach ($psr_class_map as $class_name => $tokenized_path) { $unprefixed_class_map[$psr][static::unprefixClass($class_name)] = $tokenized_path; } } $this->psrClassMap = $unprefixed_class_map; }
php
public function setPsrClassMap(array $class_map) { // Remove the leading \ from the partial namespaces. $unprefixed_class_map = array(); foreach ($class_map as $psr => $psr_class_map) { $unprefixed_class_map[$psr] = array(); foreach ($psr_class_map as $class_name => $tokenized_path) { $unprefixed_class_map[$psr][static::unprefixClass($class_name)] = $tokenized_path; } } $this->psrClassMap = $unprefixed_class_map; }
[ "public", "function", "setPsrClassMap", "(", "array", "$", "class_map", ")", "{", "// Remove the leading \\ from the partial namespaces.", "$", "unprefixed_class_map", "=", "array", "(", ")", ";", "foreach", "(", "$", "class_map", "as", "$", "psr", "=>", "$", "psr_class_map", ")", "{", "$", "unprefixed_class_map", "[", "$", "psr", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "psr_class_map", "as", "$", "class_name", "=>", "$", "tokenized_path", ")", "{", "$", "unprefixed_class_map", "[", "$", "psr", "]", "[", "static", "::", "unprefixClass", "(", "$", "class_name", ")", "]", "=", "$", "tokenized_path", ";", "}", "}", "$", "this", "->", "psrClassMap", "=", "$", "unprefixed_class_map", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/e0ipso/drupal-unit-autoload/blob/7ce147b269c7333eca31e2cd04b736d6274b9cbf/src/Loader.php#L85-L95
e0ipso/drupal-unit-autoload
src/Loader.php
Loader.autoloadPaths
protected function autoloadPaths($class) { $class = static::unprefixClass($class); // If the class that PHP is trying to find is not in the class map, built // from the composer configuration, then bail. if (!in_array($class, array_keys($this->classMap))) { return FALSE; } try { $resolver = $this->tokenResolverFactory->factory($this->classMap[$class]); $finder = $resolver->resolve(); // Have the path finder require the file and return TRUE or FALSE if it // found the file or not. $finder->requireFile($this->seed); return TRUE; } catch (ClassLoaderException $e) { // If there was an error, inform PHP that the class could not be found. return FALSE; } }
php
protected function autoloadPaths($class) { $class = static::unprefixClass($class); // If the class that PHP is trying to find is not in the class map, built // from the composer configuration, then bail. if (!in_array($class, array_keys($this->classMap))) { return FALSE; } try { $resolver = $this->tokenResolverFactory->factory($this->classMap[$class]); $finder = $resolver->resolve(); // Have the path finder require the file and return TRUE or FALSE if it // found the file or not. $finder->requireFile($this->seed); return TRUE; } catch (ClassLoaderException $e) { // If there was an error, inform PHP that the class could not be found. return FALSE; } }
[ "protected", "function", "autoloadPaths", "(", "$", "class", ")", "{", "$", "class", "=", "static", "::", "unprefixClass", "(", "$", "class", ")", ";", "// If the class that PHP is trying to find is not in the class map, built", "// from the composer configuration, then bail.", "if", "(", "!", "in_array", "(", "$", "class", ",", "array_keys", "(", "$", "this", "->", "classMap", ")", ")", ")", "{", "return", "FALSE", ";", "}", "try", "{", "$", "resolver", "=", "$", "this", "->", "tokenResolverFactory", "->", "factory", "(", "$", "this", "->", "classMap", "[", "$", "class", "]", ")", ";", "$", "finder", "=", "$", "resolver", "->", "resolve", "(", ")", ";", "// Have the path finder require the file and return TRUE or FALSE if it", "// found the file or not.", "$", "finder", "->", "requireFile", "(", "$", "this", "->", "seed", ")", ";", "return", "TRUE", ";", "}", "catch", "(", "ClassLoaderException", "$", "e", ")", "{", "// If there was an error, inform PHP that the class could not be found.", "return", "FALSE", ";", "}", "}" ]
Helper function to autoload path based files. @param string $class The requested class. @return bool TRUE if the class was found. FALSE otherwise.
[ "Helper", "function", "to", "autoload", "path", "based", "files", "." ]
train
https://github.com/e0ipso/drupal-unit-autoload/blob/7ce147b269c7333eca31e2cd04b736d6274b9cbf/src/Loader.php#L129-L148
e0ipso/drupal-unit-autoload
src/Loader.php
Loader.registerPsr
public function registerPsr(\Composer\Autoload\ClassLoader $loader) { // Composer's autoloader uses a different method to add each PSR partial // namespace. $psrs = array( 'psr-0' => 'add', 'psr-4' => 'addPsr4', ); foreach ($psrs as $psr => $loader_method) { // The $psrClassMap contains an array for psr-0 and an array for psr-4. // Each one of those contains an array where the keys are the partial // namespace, and the value is an array of tokenized paths where those // partial namespaces can be found. // Ex: // [ // 'psr-0' => [ // [ 'Drupal\\plug\\' => ['DRUPAL_CONTRIB<plug>/lib', …] ], // ], // ] foreach ($this->psrClassMap[$psr] as $partial_namespace => $tokenized_paths) { if (!is_array($tokenized_paths)) { // If a string was passed, then convert it to an array for // consistency. $tokenized_paths = array($tokenized_paths); } foreach ($tokenized_paths as $tokenized_path) { try { // Find the real path for the tokenized one. $resolver = $this->tokenResolverFactory->factory($tokenized_path); $finder = $resolver->resolve(); // Get the real path of the prefix. $real_path = $finder->find($this->seed); $loader->{$loader_method}($partial_namespace, $real_path); } catch (ClassLoaderException $e) {} } } } }
php
public function registerPsr(\Composer\Autoload\ClassLoader $loader) { // Composer's autoloader uses a different method to add each PSR partial // namespace. $psrs = array( 'psr-0' => 'add', 'psr-4' => 'addPsr4', ); foreach ($psrs as $psr => $loader_method) { // The $psrClassMap contains an array for psr-0 and an array for psr-4. // Each one of those contains an array where the keys are the partial // namespace, and the value is an array of tokenized paths where those // partial namespaces can be found. // Ex: // [ // 'psr-0' => [ // [ 'Drupal\\plug\\' => ['DRUPAL_CONTRIB<plug>/lib', …] ], // ], // ] foreach ($this->psrClassMap[$psr] as $partial_namespace => $tokenized_paths) { if (!is_array($tokenized_paths)) { // If a string was passed, then convert it to an array for // consistency. $tokenized_paths = array($tokenized_paths); } foreach ($tokenized_paths as $tokenized_path) { try { // Find the real path for the tokenized one. $resolver = $this->tokenResolverFactory->factory($tokenized_path); $finder = $resolver->resolve(); // Get the real path of the prefix. $real_path = $finder->find($this->seed); $loader->{$loader_method}($partial_namespace, $real_path); } catch (ClassLoaderException $e) {} } } } }
[ "public", "function", "registerPsr", "(", "\\", "Composer", "\\", "Autoload", "\\", "ClassLoader", "$", "loader", ")", "{", "// Composer's autoloader uses a different method to add each PSR partial", "// namespace.", "$", "psrs", "=", "array", "(", "'psr-0'", "=>", "'add'", ",", "'psr-4'", "=>", "'addPsr4'", ",", ")", ";", "foreach", "(", "$", "psrs", "as", "$", "psr", "=>", "$", "loader_method", ")", "{", "// The $psrClassMap contains an array for psr-0 and an array for psr-4.", "// Each one of those contains an array where the keys are the partial", "// namespace, and the value is an array of tokenized paths where those", "// partial namespaces can be found.", "// Ex:", "// [", "// 'psr-0' => [", "// [ 'Drupal\\\\plug\\\\' => ['DRUPAL_CONTRIB<plug>/lib', …] ],", "// ],", "// ]", "foreach", "(", "$", "this", "->", "psrClassMap", "[", "$", "psr", "]", "as", "$", "partial_namespace", "=>", "$", "tokenized_paths", ")", "{", "if", "(", "!", "is_array", "(", "$", "tokenized_paths", ")", ")", "{", "// If a string was passed, then convert it to an array for", "// consistency.", "$", "tokenized_paths", "=", "array", "(", "$", "tokenized_paths", ")", ";", "}", "foreach", "(", "$", "tokenized_paths", "as", "$", "tokenized_path", ")", "{", "try", "{", "// Find the real path for the tokenized one.", "$", "resolver", "=", "$", "this", "->", "tokenResolverFactory", "->", "factory", "(", "$", "tokenized_path", ")", ";", "$", "finder", "=", "$", "resolver", "->", "resolve", "(", ")", ";", "// Get the real path of the prefix.", "$", "real_path", "=", "$", "finder", "->", "find", "(", "$", "this", "->", "seed", ")", ";", "$", "loader", "->", "{", "$", "loader_method", "}", "(", "$", "partial_namespace", ",", "$", "real_path", ")", ";", "}", "catch", "(", "ClassLoaderException", "$", "e", ")", "{", "}", "}", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/e0ipso/drupal-unit-autoload/blob/7ce147b269c7333eca31e2cd04b736d6274b9cbf/src/Loader.php#L153-L190
baleen/cli
src/Provider/ApplicationProvider.php
ApplicationProvider.register
public function register() { $container = $this->getContainer(); $container->singleton(Services::APPLICATION_DISPATCHER, EventDispatcher::class); if (!$container->isRegistered(Services::APPLICATION)) { $args = [ Services::COMMANDS, Services::HELPERSET, Services::APPLICATION_DISPATCHER, ]; $container->singleton(Services::APPLICATION, Application::class) ->withArguments($args); } // register inflectors for the different types of commands $container->inflector(RepositoryAwareInterface::class) ->invokeMethods([ 'setRepository' => [Services::REPOSITORY], 'setFilesystem' => [Services::REPOSITORY_FILESYSTEM], ]); $container->inflector(StorageAwareInterface::class) ->invokeMethod('setStorage', [Services::STORAGE]); $container->inflector(TimelineAwareInterface::class) ->invokeMethod('setTimeline', [Services::TIMELINE]); $container->inflector(ComparatorAwareInterface::class) ->invokeMethod('setComparator', [Services::COMPARATOR]); $container->inflector(ConfigStorageAwareInterface::class) ->invokeMethod('setConfigStorage', [Services::CONFIG_STORAGE]); $container->inflector(AbstractMessage::class) ->invokeMethod('setConfig', [Services::CONFIG]); }
php
public function register() { $container = $this->getContainer(); $container->singleton(Services::APPLICATION_DISPATCHER, EventDispatcher::class); if (!$container->isRegistered(Services::APPLICATION)) { $args = [ Services::COMMANDS, Services::HELPERSET, Services::APPLICATION_DISPATCHER, ]; $container->singleton(Services::APPLICATION, Application::class) ->withArguments($args); } // register inflectors for the different types of commands $container->inflector(RepositoryAwareInterface::class) ->invokeMethods([ 'setRepository' => [Services::REPOSITORY], 'setFilesystem' => [Services::REPOSITORY_FILESYSTEM], ]); $container->inflector(StorageAwareInterface::class) ->invokeMethod('setStorage', [Services::STORAGE]); $container->inflector(TimelineAwareInterface::class) ->invokeMethod('setTimeline', [Services::TIMELINE]); $container->inflector(ComparatorAwareInterface::class) ->invokeMethod('setComparator', [Services::COMPARATOR]); $container->inflector(ConfigStorageAwareInterface::class) ->invokeMethod('setConfigStorage', [Services::CONFIG_STORAGE]); $container->inflector(AbstractMessage::class) ->invokeMethod('setConfig', [Services::CONFIG]); }
[ "public", "function", "register", "(", ")", "{", "$", "container", "=", "$", "this", "->", "getContainer", "(", ")", ";", "$", "container", "->", "singleton", "(", "Services", "::", "APPLICATION_DISPATCHER", ",", "EventDispatcher", "::", "class", ")", ";", "if", "(", "!", "$", "container", "->", "isRegistered", "(", "Services", "::", "APPLICATION", ")", ")", "{", "$", "args", "=", "[", "Services", "::", "COMMANDS", ",", "Services", "::", "HELPERSET", ",", "Services", "::", "APPLICATION_DISPATCHER", ",", "]", ";", "$", "container", "->", "singleton", "(", "Services", "::", "APPLICATION", ",", "Application", "::", "class", ")", "->", "withArguments", "(", "$", "args", ")", ";", "}", "// register inflectors for the different types of commands", "$", "container", "->", "inflector", "(", "RepositoryAwareInterface", "::", "class", ")", "->", "invokeMethods", "(", "[", "'setRepository'", "=>", "[", "Services", "::", "REPOSITORY", "]", ",", "'setFilesystem'", "=>", "[", "Services", "::", "REPOSITORY_FILESYSTEM", "]", ",", "]", ")", ";", "$", "container", "->", "inflector", "(", "StorageAwareInterface", "::", "class", ")", "->", "invokeMethod", "(", "'setStorage'", ",", "[", "Services", "::", "STORAGE", "]", ")", ";", "$", "container", "->", "inflector", "(", "TimelineAwareInterface", "::", "class", ")", "->", "invokeMethod", "(", "'setTimeline'", ",", "[", "Services", "::", "TIMELINE", "]", ")", ";", "$", "container", "->", "inflector", "(", "ComparatorAwareInterface", "::", "class", ")", "->", "invokeMethod", "(", "'setComparator'", ",", "[", "Services", "::", "COMPARATOR", "]", ")", ";", "$", "container", "->", "inflector", "(", "ConfigStorageAwareInterface", "::", "class", ")", "->", "invokeMethod", "(", "'setConfigStorage'", ",", "[", "Services", "::", "CONFIG_STORAGE", "]", ")", ";", "$", "container", "->", "inflector", "(", "AbstractMessage", "::", "class", ")", "->", "invokeMethod", "(", "'setConfig'", ",", "[", "Services", "::", "CONFIG", "]", ")", ";", "}" ]
Use the register method to register items with the container via the protected $this->container property or the `getContainer` method from the ContainerAwareTrait.
[ "Use", "the", "register", "method", "to", "register", "items", "with", "the", "container", "via", "the", "protected", "$this", "-", ">", "container", "property", "or", "the", "getContainer", "method", "from", "the", "ContainerAwareTrait", "." ]
train
https://github.com/baleen/cli/blob/2ecbc7179c5800c9075fd93204ef25da375536ed/src/Provider/ApplicationProvider.php#L51-L88
czim/laravel-pxlcms
src/Generator/Writer/Model/ModelWriterContext.php
ModelWriterContext.getModelNamespaceForSpecialModel
public function getModelNamespaceForSpecialModel($type) { $typeName = $this->getConfigNameForStandardModelType($type); if ( ! is_null($typeName) && config('pxlcms.generator.models.include_namespace_of_standard_models') ) { return $this->getClassNameFromNamespace(config('pxlcms.generator.standard_models.' . $typeName)); } return '\\' . config('pxlcms.generator.standard_models.' . $typeName); }
php
public function getModelNamespaceForSpecialModel($type) { $typeName = $this->getConfigNameForStandardModelType($type); if ( ! is_null($typeName) && config('pxlcms.generator.models.include_namespace_of_standard_models') ) { return $this->getClassNameFromNamespace(config('pxlcms.generator.standard_models.' . $typeName)); } return '\\' . config('pxlcms.generator.standard_models.' . $typeName); }
[ "public", "function", "getModelNamespaceForSpecialModel", "(", "$", "type", ")", "{", "$", "typeName", "=", "$", "this", "->", "getConfigNameForStandardModelType", "(", "$", "type", ")", ";", "if", "(", "!", "is_null", "(", "$", "typeName", ")", "&&", "config", "(", "'pxlcms.generator.models.include_namespace_of_standard_models'", ")", ")", "{", "return", "$", "this", "->", "getClassNameFromNamespace", "(", "config", "(", "'pxlcms.generator.standard_models.'", ".", "$", "typeName", ")", ")", ";", "}", "return", "'\\\\'", ".", "config", "(", "'pxlcms.generator.standard_models.'", ".", "$", "typeName", ")", ";", "}" ]
Returns the model name (FQN if not to be imported) for a standard model based on CmsModel const values for RELATION_TYPEs @param int $type @return string
[ "Returns", "the", "model", "name", "(", "FQN", "if", "not", "to", "be", "imported", ")", "for", "a", "standard", "model", "based", "on", "CmsModel", "const", "values", "for", "RELATION_TYPEs" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Writer/Model/ModelWriterContext.php#L84-L95
czim/laravel-pxlcms
src/Generator/Writer/Model/ModelWriterContext.php
ModelWriterContext.getConfigNameForStandardModelType
protected function getConfigNameForStandardModelType($type) { switch ($type) { case CmsModel::RELATION_TYPE_IMAGE: return 'image'; case CmsModel::RELATION_TYPE_FILE: return 'file'; case CmsModel::RELATION_TYPE_CATEGORY: return 'category'; case CmsModel::RELATION_TYPE_CHECKBOX: return 'checkbox'; // default omitted on purpose } return null; }
php
protected function getConfigNameForStandardModelType($type) { switch ($type) { case CmsModel::RELATION_TYPE_IMAGE: return 'image'; case CmsModel::RELATION_TYPE_FILE: return 'file'; case CmsModel::RELATION_TYPE_CATEGORY: return 'category'; case CmsModel::RELATION_TYPE_CHECKBOX: return 'checkbox'; // default omitted on purpose } return null; }
[ "protected", "function", "getConfigNameForStandardModelType", "(", "$", "type", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "CmsModel", "::", "RELATION_TYPE_IMAGE", ":", "return", "'image'", ";", "case", "CmsModel", "::", "RELATION_TYPE_FILE", ":", "return", "'file'", ";", "case", "CmsModel", "::", "RELATION_TYPE_CATEGORY", ":", "return", "'category'", ";", "case", "CmsModel", "::", "RELATION_TYPE_CHECKBOX", ":", "return", "'checkbox'", ";", "// default omitted on purpose", "}", "return", "null", ";", "}" ]
Returns the special model type name used for config properties based on CmsModel const values for RELATION_TYPEs @param int $type @return null|string
[ "Returns", "the", "special", "model", "type", "name", "used", "for", "config", "properties", "based", "on", "CmsModel", "const", "values", "for", "RELATION_TYPEs" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Generator/Writer/Model/ModelWriterContext.php#L104-L124
fuelphp/display
src/ViewManager.php
ViewManager.configure
protected function configure(array $config) { if (isset($config['parsers'])) { $this->registerParsers($config['parsers']); } if (isset($config['cache'])) { $this->cachePath = rtrim('cache', '\\/').DIRECTORY_SEPARATOR; } if (isset($config['auto_filter'])) { $this->autoFilter = (bool) $config['auto_filter']; } if (isset($config['view_folder'])) { $this->setViewFolder($config['view_folder']); } if (isset($config['whitelist'])) { $this->whitelist($config['whitelist']); } }
php
protected function configure(array $config) { if (isset($config['parsers'])) { $this->registerParsers($config['parsers']); } if (isset($config['cache'])) { $this->cachePath = rtrim('cache', '\\/').DIRECTORY_SEPARATOR; } if (isset($config['auto_filter'])) { $this->autoFilter = (bool) $config['auto_filter']; } if (isset($config['view_folder'])) { $this->setViewFolder($config['view_folder']); } if (isset($config['whitelist'])) { $this->whitelist($config['whitelist']); } }
[ "protected", "function", "configure", "(", "array", "$", "config", ")", "{", "if", "(", "isset", "(", "$", "config", "[", "'parsers'", "]", ")", ")", "{", "$", "this", "->", "registerParsers", "(", "$", "config", "[", "'parsers'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'cache'", "]", ")", ")", "{", "$", "this", "->", "cachePath", "=", "rtrim", "(", "'cache'", ",", "'\\\\/'", ")", ".", "DIRECTORY_SEPARATOR", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'auto_filter'", "]", ")", ")", "{", "$", "this", "->", "autoFilter", "=", "(", "bool", ")", "$", "config", "[", "'auto_filter'", "]", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'view_folder'", "]", ")", ")", "{", "$", "this", "->", "setViewFolder", "(", "$", "config", "[", "'view_folder'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'whitelist'", "]", ")", ")", "{", "$", "this", "->", "whitelist", "(", "$", "config", "[", "'whitelist'", "]", ")", ";", "}", "}" ]
Configures the view manager @param array $config
[ "Configures", "the", "view", "manager" ]
train
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/ViewManager.php#L59-L85
fuelphp/display
src/ViewManager.php
ViewManager.whitelist
public function whitelist($classes) { if ( ! is_array($classes)) { $classes = func_get_args(); } $this->whitelist = array_unique(array_merge($this->whitelist, $classes)); }
php
public function whitelist($classes) { if ( ! is_array($classes)) { $classes = func_get_args(); } $this->whitelist = array_unique(array_merge($this->whitelist, $classes)); }
[ "public", "function", "whitelist", "(", "$", "classes", ")", "{", "if", "(", "!", "is_array", "(", "$", "classes", ")", ")", "{", "$", "classes", "=", "func_get_args", "(", ")", ";", "}", "$", "this", "->", "whitelist", "=", "array_unique", "(", "array_merge", "(", "$", "this", "->", "whitelist", ",", "$", "classes", ")", ")", ";", "}" ]
Adds the given classes to the whitelist. @param string[] $classes
[ "Adds", "the", "given", "classes", "to", "the", "whitelist", "." ]
train
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/ViewManager.php#L102-L110
fuelphp/display
src/ViewManager.php
ViewManager.registerParser
public function registerParser($extension, Parser $parser) { if ($parser instanceof ViewManagerAware) { $parser->setViewManager($this); } $this->parsers[$extension] = $parser; }
php
public function registerParser($extension, Parser $parser) { if ($parser instanceof ViewManagerAware) { $parser->setViewManager($this); } $this->parsers[$extension] = $parser; }
[ "public", "function", "registerParser", "(", "$", "extension", ",", "Parser", "$", "parser", ")", "{", "if", "(", "$", "parser", "instanceof", "ViewManagerAware", ")", "{", "$", "parser", "->", "setViewManager", "(", "$", "this", ")", ";", "}", "$", "this", "->", "parsers", "[", "$", "extension", "]", "=", "$", "parser", ";", "}" ]
Registers a new parser for rendering a given file type @param string $extension @param Parser $parser
[ "Registers", "a", "new", "parser", "for", "rendering", "a", "given", "file", "type" ]
train
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/ViewManager.php#L118-L126
fuelphp/display
src/ViewManager.php
ViewManager.registerParsers
public function registerParsers(array $parsers) { foreach ($parsers as $extension => $parser) { $this->registerParser($extension, $parser); } }
php
public function registerParsers(array $parsers) { foreach ($parsers as $extension => $parser) { $this->registerParser($extension, $parser); } }
[ "public", "function", "registerParsers", "(", "array", "$", "parsers", ")", "{", "foreach", "(", "$", "parsers", "as", "$", "extension", "=>", "$", "parser", ")", "{", "$", "this", "->", "registerParser", "(", "$", "extension", ",", "$", "parser", ")", ";", "}", "}" ]
Registers multiple parsers at once @param array $parsers Key as the file extension and value as the parser instance
[ "Registers", "multiple", "parsers", "at", "once" ]
train
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/ViewManager.php#L133-L139
fuelphp/display
src/ViewManager.php
ViewManager.findView
public function findView($view) { $view = $this->viewFolder.DIRECTORY_SEPARATOR.ltrim($view, DIRECTORY_SEPARATOR); return $this->finder->findFileReversed($view); }
php
public function findView($view) { $view = $this->viewFolder.DIRECTORY_SEPARATOR.ltrim($view, DIRECTORY_SEPARATOR); return $this->finder->findFileReversed($view); }
[ "public", "function", "findView", "(", "$", "view", ")", "{", "$", "view", "=", "$", "this", "->", "viewFolder", ".", "DIRECTORY_SEPARATOR", ".", "ltrim", "(", "$", "view", ",", "DIRECTORY_SEPARATOR", ")", ";", "return", "$", "this", "->", "finder", "->", "findFileReversed", "(", "$", "view", ")", ";", "}" ]
Attempts to get the file name for the given view @param $view @return array|\Fuel\FileSystem\Directory|\Fuel\FileSystem\File|string
[ "Attempts", "to", "get", "the", "file", "name", "for", "the", "given", "view" ]
train
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/ViewManager.php#L191-L196
fuelphp/display
src/ViewManager.php
ViewManager.forge
public function forge($view, array $data = null, $filter = null) { if ( ! $file = $this->findView($view)) { throw new Exception\ViewNotFound('Could not locate view: '.$view); } if ($filter === null) { $filter = $this->autoFilter; } $extension = pathinfo($file, PATHINFO_EXTENSION); if ( ! isset($this->parsers[$extension])) { throw new \DomainException('Could not find parser for extension: '.$extension); } $parser = $this->parsers[$extension]; $view = new View($this, $parser, $file, $filter); if ($data) { $view->set($data); } return $view; }
php
public function forge($view, array $data = null, $filter = null) { if ( ! $file = $this->findView($view)) { throw new Exception\ViewNotFound('Could not locate view: '.$view); } if ($filter === null) { $filter = $this->autoFilter; } $extension = pathinfo($file, PATHINFO_EXTENSION); if ( ! isset($this->parsers[$extension])) { throw new \DomainException('Could not find parser for extension: '.$extension); } $parser = $this->parsers[$extension]; $view = new View($this, $parser, $file, $filter); if ($data) { $view->set($data); } return $view; }
[ "public", "function", "forge", "(", "$", "view", ",", "array", "$", "data", "=", "null", ",", "$", "filter", "=", "null", ")", "{", "if", "(", "!", "$", "file", "=", "$", "this", "->", "findView", "(", "$", "view", ")", ")", "{", "throw", "new", "Exception", "\\", "ViewNotFound", "(", "'Could not locate view: '", ".", "$", "view", ")", ";", "}", "if", "(", "$", "filter", "===", "null", ")", "{", "$", "filter", "=", "$", "this", "->", "autoFilter", ";", "}", "$", "extension", "=", "pathinfo", "(", "$", "file", ",", "PATHINFO_EXTENSION", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "parsers", "[", "$", "extension", "]", ")", ")", "{", "throw", "new", "\\", "DomainException", "(", "'Could not find parser for extension: '", ".", "$", "extension", ")", ";", "}", "$", "parser", "=", "$", "this", "->", "parsers", "[", "$", "extension", "]", ";", "$", "view", "=", "new", "View", "(", "$", "this", ",", "$", "parser", ",", "$", "file", ",", "$", "filter", ")", ";", "if", "(", "$", "data", ")", "{", "$", "view", "->", "set", "(", "$", "data", ")", ";", "}", "return", "$", "view", ";", "}" ]
Attempts to find and load the given view @param string $view @param array $data @param null|bool $filter @return View @throws Exception\ViewNotFound If the given view cannot be found @throws \DomainException If a parser for the view cannot be found
[ "Attempts", "to", "find", "and", "load", "the", "given", "view" ]
train
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/ViewManager.php#L210-L238
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.attributesToArray
public function attributesToArray() { // unset date values that are 0, so they don't cause problems with serializeDate() foreach ($this->getDates() as $key) { if ( ! isset($this->attributes[$key])) continue; // 0 should be considered 'unset' aswell if (0 === $this->attributes[$key]) { $this->attributes[$key] = null; } } return parent::attributesToArray(); }
php
public function attributesToArray() { // unset date values that are 0, so they don't cause problems with serializeDate() foreach ($this->getDates() as $key) { if ( ! isset($this->attributes[$key])) continue; // 0 should be considered 'unset' aswell if (0 === $this->attributes[$key]) { $this->attributes[$key] = null; } } return parent::attributesToArray(); }
[ "public", "function", "attributesToArray", "(", ")", "{", "// unset date values that are 0, so they don't cause problems with serializeDate()", "foreach", "(", "$", "this", "->", "getDates", "(", ")", "as", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "attributes", "[", "$", "key", "]", ")", ")", "continue", ";", "// 0 should be considered 'unset' aswell", "if", "(", "0", "===", "$", "this", "->", "attributes", "[", "$", "key", "]", ")", "{", "$", "this", "->", "attributes", "[", "$", "key", "]", "=", "null", ";", "}", "}", "return", "parent", "::", "attributesToArray", "(", ")", ";", "}" ]
Convert the model's attributes to an array. @inheritdoc
[ "Convert", "the", "model", "s", "attributes", "to", "an", "array", "." ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L186-L199
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getTable
public function getTable() { if (isset($this->table)) { return $this->table; } $moduleNumber = $this->getModuleNumber(); $baseName = str_replace('\\', '', Str::snake(Str::plural(class_basename($this)))); // if it is a translated table, convert to CMS convention $translationExtension = '_' . str_plural(strtolower(config('translatable.translation_suffix', 'translation'))); if (ends_with($baseName, $translationExtension)) { $baseName = str_plural(substr($baseName, 0, -1 * strlen($translationExtension))) . config('pxlcms.translatable.translation_table_postfix'); } return config('pxlcms.tables.prefix') . ($moduleNumber ? 'm' . $moduleNumber . '_' : '') . $baseName; }
php
public function getTable() { if (isset($this->table)) { return $this->table; } $moduleNumber = $this->getModuleNumber(); $baseName = str_replace('\\', '', Str::snake(Str::plural(class_basename($this)))); // if it is a translated table, convert to CMS convention $translationExtension = '_' . str_plural(strtolower(config('translatable.translation_suffix', 'translation'))); if (ends_with($baseName, $translationExtension)) { $baseName = str_plural(substr($baseName, 0, -1 * strlen($translationExtension))) . config('pxlcms.translatable.translation_table_postfix'); } return config('pxlcms.tables.prefix') . ($moduleNumber ? 'm' . $moduleNumber . '_' : '') . $baseName; }
[ "public", "function", "getTable", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "table", ")", ")", "{", "return", "$", "this", "->", "table", ";", "}", "$", "moduleNumber", "=", "$", "this", "->", "getModuleNumber", "(", ")", ";", "$", "baseName", "=", "str_replace", "(", "'\\\\'", ",", "''", ",", "Str", "::", "snake", "(", "Str", "::", "plural", "(", "class_basename", "(", "$", "this", ")", ")", ")", ")", ";", "// if it is a translated table, convert to CMS convention", "$", "translationExtension", "=", "'_'", ".", "str_plural", "(", "strtolower", "(", "config", "(", "'translatable.translation_suffix'", ",", "'translation'", ")", ")", ")", ";", "if", "(", "ends_with", "(", "$", "baseName", ",", "$", "translationExtension", ")", ")", "{", "$", "baseName", "=", "str_plural", "(", "substr", "(", "$", "baseName", ",", "0", ",", "-", "1", "*", "strlen", "(", "$", "translationExtension", ")", ")", ")", ".", "config", "(", "'pxlcms.translatable.translation_table_postfix'", ")", ";", "}", "return", "config", "(", "'pxlcms.tables.prefix'", ")", ".", "(", "$", "moduleNumber", "?", "'m'", ".", "$", "moduleNumber", ".", "'_'", ":", "''", ")", ".", "$", "baseName", ";", "}" ]
Get the table associated with the model. @return string
[ "Get", "the", "table", "associated", "with", "the", "model", "." ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L221-L242
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getCmsReferenceKeyForRelation
public function getCmsReferenceKeyForRelation($relation, $reversed = false) { $isParent = ( array_key_exists($relation, $this->relationsConfig) && array_key_exists('parent', $this->relationsConfig[$relation]) && (bool) $this->relationsConfig[$relation]['parent'] ); if ($reversed) { $isParent = ! $isParent; } return $isParent ? config('pxlcms.relations.references.keys.to', 'to_entry_id') : config('pxlcms.relations.references.keys.from', 'from_entry_id'); }
php
public function getCmsReferenceKeyForRelation($relation, $reversed = false) { $isParent = ( array_key_exists($relation, $this->relationsConfig) && array_key_exists('parent', $this->relationsConfig[$relation]) && (bool) $this->relationsConfig[$relation]['parent'] ); if ($reversed) { $isParent = ! $isParent; } return $isParent ? config('pxlcms.relations.references.keys.to', 'to_entry_id') : config('pxlcms.relations.references.keys.from', 'from_entry_id'); }
[ "public", "function", "getCmsReferenceKeyForRelation", "(", "$", "relation", ",", "$", "reversed", "=", "false", ")", "{", "$", "isParent", "=", "(", "array_key_exists", "(", "$", "relation", ",", "$", "this", "->", "relationsConfig", ")", "&&", "array_key_exists", "(", "'parent'", ",", "$", "this", "->", "relationsConfig", "[", "$", "relation", "]", ")", "&&", "(", "bool", ")", "$", "this", "->", "relationsConfig", "[", "$", "relation", "]", "[", "'parent'", "]", ")", ";", "if", "(", "$", "reversed", ")", "{", "$", "isParent", "=", "!", "$", "isParent", ";", "}", "return", "$", "isParent", "?", "config", "(", "'pxlcms.relations.references.keys.to'", ",", "'to_entry_id'", ")", ":", "config", "(", "'pxlcms.relations.references.keys.from'", ",", "'from_entry_id'", ")", ";", "}" ]
Get standard belongsToMany reference key name for 'from' and 'to' models Reversed gives the 'to' key @param string $relation @param bool $reversed (default: false) @return string
[ "Get", "standard", "belongsToMany", "reference", "key", "name", "for", "from", "and", "to", "models", "Reversed", "gives", "the", "to", "key" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L276-L290
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getCmsReferenceFieldId
public function getCmsReferenceFieldId($relation) { if ( ! array_key_exists($relation, $this->relationsConfig) || ! array_key_exists('field', $this->relationsConfig[$relation]) ) { return null; } return (int) $this->relationsConfig[ $relation ]['field']; }
php
public function getCmsReferenceFieldId($relation) { if ( ! array_key_exists($relation, $this->relationsConfig) || ! array_key_exists('field', $this->relationsConfig[$relation]) ) { return null; } return (int) $this->relationsConfig[ $relation ]['field']; }
[ "public", "function", "getCmsReferenceFieldId", "(", "$", "relation", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "relation", ",", "$", "this", "->", "relationsConfig", ")", "||", "!", "array_key_exists", "(", "'field'", ",", "$", "this", "->", "relationsConfig", "[", "$", "relation", "]", ")", ")", "{", "return", "null", ";", "}", "return", "(", "int", ")", "$", "this", "->", "relationsConfig", "[", "$", "relation", "]", "[", "'field'", "]", ";", "}" ]
Returns the configured 'from_field_id' field id value for the reference relation @param string $relation @return int|null
[ "Returns", "the", "configured", "from_field_id", "field", "id", "value", "for", "the", "reference", "relation" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L298-L307
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getCmsSpecialRelationType
public function getCmsSpecialRelationType($relation) { if ( ! array_key_exists($relation, $this->relationsConfig) || ! array_key_exists('type', $this->relationsConfig[$relation]) ) { return null; } return $this->relationsConfig[ $relation ]['type']; }
php
public function getCmsSpecialRelationType($relation) { if ( ! array_key_exists($relation, $this->relationsConfig) || ! array_key_exists('type', $this->relationsConfig[$relation]) ) { return null; } return $this->relationsConfig[ $relation ]['type']; }
[ "public", "function", "getCmsSpecialRelationType", "(", "$", "relation", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "relation", ",", "$", "this", "->", "relationsConfig", ")", "||", "!", "array_key_exists", "(", "'type'", ",", "$", "this", "->", "relationsConfig", "[", "$", "relation", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "relationsConfig", "[", "$", "relation", "]", "[", "'type'", "]", ";", "}" ]
Returns the configured special standard model type for the reference relation @param string $relation @return string|null
[ "Returns", "the", "configured", "special", "standard", "model", "type", "for", "the", "reference", "relation" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L315-L324
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getCmsSpecialRelationTranslated
public function getCmsSpecialRelationTranslated($relation) { if ( ! array_key_exists($relation, $this->relationsConfig) || ! array_key_exists('translated', $this->relationsConfig[$relation]) ) { return false; } return (bool) $this->relationsConfig[ $relation ]['translated']; }
php
public function getCmsSpecialRelationTranslated($relation) { if ( ! array_key_exists($relation, $this->relationsConfig) || ! array_key_exists('translated', $this->relationsConfig[$relation]) ) { return false; } return (bool) $this->relationsConfig[ $relation ]['translated']; }
[ "public", "function", "getCmsSpecialRelationTranslated", "(", "$", "relation", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "relation", ",", "$", "this", "->", "relationsConfig", ")", "||", "!", "array_key_exists", "(", "'translated'", ",", "$", "this", "->", "relationsConfig", "[", "$", "relation", "]", ")", ")", "{", "return", "false", ";", "}", "return", "(", "bool", ")", "$", "this", "->", "relationsConfig", "[", "$", "relation", "]", "[", "'translated'", "]", ";", "}" ]
Returns whether the special standard model relation is translated (locale-dependent) @param string $relation @return string|null
[ "Returns", "whether", "the", "special", "standard", "model", "relation", "is", "translated", "(", "locale", "-", "dependent", ")" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L333-L342
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.belongsTo
public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null) { // If no relation name was given, we will use this debug backtrace to extract // the calling method's name and use that as the relationship name as most // of the time this will be what we desire to use for the relationships. if (is_null($relation)) { list($current, $caller) = debug_backtrace(false, 2); $relation = $caller['function']; } $specialType = $this->getCmsSpecialRelationType($relation); // If no foreign key was supplied, we can use a backtrace to guess the proper // foreign key name by using the name of the relationship function, which // when combined with an "_id" should conventionally match the columns. if (is_null($foreignKey)) { if ($specialType === self::RELATION_TYPE_CATEGORY) { $foreignKey = config('pxlcms.relations.categories.keys.category'); } else { $foreignKey = Str::snake($relation); } } // If the relation name is the same (casing aside) as the foreign key attribute, // we must make sure that the foreign key property is at least a key in the // attributes array. If it is not, there will be recursive lookup problems // where the attribute is never resolved and 'property does not exist' exceptions occur. if ( snake_case($relation) == $foreignKey && ! array_key_exists($foreignKey, $this->attributes) ) { $this->attributes[ $foreignKey ] = null; } /** @var Builder $belongsTo */ $belongsTo = parent::belongsTo($related, $foreignKey, $otherKey, $relation); // category relation must be filtered by module id if ($specialType === self::RELATION_TYPE_CATEGORY) { $belongsTo->where( config('pxlcms.relations.categories.keys.module'), $this->getModuleNumber() ); } return $belongsTo; }
php
public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null) { // If no relation name was given, we will use this debug backtrace to extract // the calling method's name and use that as the relationship name as most // of the time this will be what we desire to use for the relationships. if (is_null($relation)) { list($current, $caller) = debug_backtrace(false, 2); $relation = $caller['function']; } $specialType = $this->getCmsSpecialRelationType($relation); // If no foreign key was supplied, we can use a backtrace to guess the proper // foreign key name by using the name of the relationship function, which // when combined with an "_id" should conventionally match the columns. if (is_null($foreignKey)) { if ($specialType === self::RELATION_TYPE_CATEGORY) { $foreignKey = config('pxlcms.relations.categories.keys.category'); } else { $foreignKey = Str::snake($relation); } } // If the relation name is the same (casing aside) as the foreign key attribute, // we must make sure that the foreign key property is at least a key in the // attributes array. If it is not, there will be recursive lookup problems // where the attribute is never resolved and 'property does not exist' exceptions occur. if ( snake_case($relation) == $foreignKey && ! array_key_exists($foreignKey, $this->attributes) ) { $this->attributes[ $foreignKey ] = null; } /** @var Builder $belongsTo */ $belongsTo = parent::belongsTo($related, $foreignKey, $otherKey, $relation); // category relation must be filtered by module id if ($specialType === self::RELATION_TYPE_CATEGORY) { $belongsTo->where( config('pxlcms.relations.categories.keys.module'), $this->getModuleNumber() ); } return $belongsTo; }
[ "public", "function", "belongsTo", "(", "$", "related", ",", "$", "foreignKey", "=", "null", ",", "$", "otherKey", "=", "null", ",", "$", "relation", "=", "null", ")", "{", "// If no relation name was given, we will use this debug backtrace to extract", "// the calling method's name and use that as the relationship name as most", "// of the time this will be what we desire to use for the relationships.", "if", "(", "is_null", "(", "$", "relation", ")", ")", "{", "list", "(", "$", "current", ",", "$", "caller", ")", "=", "debug_backtrace", "(", "false", ",", "2", ")", ";", "$", "relation", "=", "$", "caller", "[", "'function'", "]", ";", "}", "$", "specialType", "=", "$", "this", "->", "getCmsSpecialRelationType", "(", "$", "relation", ")", ";", "// If no foreign key was supplied, we can use a backtrace to guess the proper", "// foreign key name by using the name of the relationship function, which", "// when combined with an \"_id\" should conventionally match the columns.", "if", "(", "is_null", "(", "$", "foreignKey", ")", ")", "{", "if", "(", "$", "specialType", "===", "self", "::", "RELATION_TYPE_CATEGORY", ")", "{", "$", "foreignKey", "=", "config", "(", "'pxlcms.relations.categories.keys.category'", ")", ";", "}", "else", "{", "$", "foreignKey", "=", "Str", "::", "snake", "(", "$", "relation", ")", ";", "}", "}", "// If the relation name is the same (casing aside) as the foreign key attribute,", "// we must make sure that the foreign key property is at least a key in the", "// attributes array. If it is not, there will be recursive lookup problems", "// where the attribute is never resolved and 'property does not exist' exceptions occur.", "if", "(", "snake_case", "(", "$", "relation", ")", "==", "$", "foreignKey", "&&", "!", "array_key_exists", "(", "$", "foreignKey", ",", "$", "this", "->", "attributes", ")", ")", "{", "$", "this", "->", "attributes", "[", "$", "foreignKey", "]", "=", "null", ";", "}", "/** @var Builder $belongsTo */", "$", "belongsTo", "=", "parent", "::", "belongsTo", "(", "$", "related", ",", "$", "foreignKey", ",", "$", "otherKey", ",", "$", "relation", ")", ";", "// category relation must be filtered by module id", "if", "(", "$", "specialType", "===", "self", "::", "RELATION_TYPE_CATEGORY", ")", "{", "$", "belongsTo", "->", "where", "(", "config", "(", "'pxlcms.relations.categories.keys.module'", ")", ",", "$", "this", "->", "getModuleNumber", "(", ")", ")", ";", "}", "return", "$", "belongsTo", ";", "}" ]
Override for different naming convention @param string $related @param string $foreignKey @param string $otherKey @param string $relation @return \Illuminate\Database\Eloquent\Relations\BelongsTo
[ "Override", "for", "different", "naming", "convention" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L354-L400
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.belongsToMany
public function belongsToMany($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null) { // If no relationship name was passed, we will pull backtraces to get the // name of the calling function. We will use that function name as the // title of this relation since that is a great convention to apply. if (is_null($relation)) { $relation = $this->getBelongsToManyCaller(); } $foreignKey = $foreignKey ?: $this->getCmsReferenceKeyForRelation($relation); $otherKey = $otherKey ?: $this->getCmsReferenceKeyForRelation($relation, true); if (is_null($table)) { $table = $this->getCmsJoiningTable(); } $fieldId = $this->getCmsReferenceFieldId($relation); if (empty($fieldId)) { throw new InvalidArgumentException("No 'field' id configured for relation/reference: '{$relation}'!"); } // originally, it was possible to just get the parent's BelongsToMany instance, but // to avoid problems when saving on the relationship, we need a specialized extension // of the relation class for the CMS. //$belongsToMany = parent::belongsToMany($related, $table, $foreignKey, $otherKey); /** @var Model $instance */ $instance = new $related; $query = $instance->newQuery(); $belongsToMany = new BelongsToMany($query, $this, $table, $foreignKey, $otherKey, $relation, $fieldId); // add constraints $belongsToMany->wherePivot(config('pxlcms.relations.references.keys.field', 'from_field_id'), $fieldId); return $belongsToMany; }
php
public function belongsToMany($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null) { // If no relationship name was passed, we will pull backtraces to get the // name of the calling function. We will use that function name as the // title of this relation since that is a great convention to apply. if (is_null($relation)) { $relation = $this->getBelongsToManyCaller(); } $foreignKey = $foreignKey ?: $this->getCmsReferenceKeyForRelation($relation); $otherKey = $otherKey ?: $this->getCmsReferenceKeyForRelation($relation, true); if (is_null($table)) { $table = $this->getCmsJoiningTable(); } $fieldId = $this->getCmsReferenceFieldId($relation); if (empty($fieldId)) { throw new InvalidArgumentException("No 'field' id configured for relation/reference: '{$relation}'!"); } // originally, it was possible to just get the parent's BelongsToMany instance, but // to avoid problems when saving on the relationship, we need a specialized extension // of the relation class for the CMS. //$belongsToMany = parent::belongsToMany($related, $table, $foreignKey, $otherKey); /** @var Model $instance */ $instance = new $related; $query = $instance->newQuery(); $belongsToMany = new BelongsToMany($query, $this, $table, $foreignKey, $otherKey, $relation, $fieldId); // add constraints $belongsToMany->wherePivot(config('pxlcms.relations.references.keys.field', 'from_field_id'), $fieldId); return $belongsToMany; }
[ "public", "function", "belongsToMany", "(", "$", "related", ",", "$", "table", "=", "null", ",", "$", "foreignKey", "=", "null", ",", "$", "otherKey", "=", "null", ",", "$", "relation", "=", "null", ")", "{", "// If no relationship name was passed, we will pull backtraces to get the", "// name of the calling function. We will use that function name as the", "// title of this relation since that is a great convention to apply.", "if", "(", "is_null", "(", "$", "relation", ")", ")", "{", "$", "relation", "=", "$", "this", "->", "getBelongsToManyCaller", "(", ")", ";", "}", "$", "foreignKey", "=", "$", "foreignKey", "?", ":", "$", "this", "->", "getCmsReferenceKeyForRelation", "(", "$", "relation", ")", ";", "$", "otherKey", "=", "$", "otherKey", "?", ":", "$", "this", "->", "getCmsReferenceKeyForRelation", "(", "$", "relation", ",", "true", ")", ";", "if", "(", "is_null", "(", "$", "table", ")", ")", "{", "$", "table", "=", "$", "this", "->", "getCmsJoiningTable", "(", ")", ";", "}", "$", "fieldId", "=", "$", "this", "->", "getCmsReferenceFieldId", "(", "$", "relation", ")", ";", "if", "(", "empty", "(", "$", "fieldId", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"No 'field' id configured for relation/reference: '{$relation}'!\"", ")", ";", "}", "// originally, it was possible to just get the parent's BelongsToMany instance, but", "// to avoid problems when saving on the relationship, we need a specialized extension", "// of the relation class for the CMS.", "//$belongsToMany = parent::belongsToMany($related, $table, $foreignKey, $otherKey);", "/** @var Model $instance */", "$", "instance", "=", "new", "$", "related", ";", "$", "query", "=", "$", "instance", "->", "newQuery", "(", ")", ";", "$", "belongsToMany", "=", "new", "BelongsToMany", "(", "$", "query", ",", "$", "this", ",", "$", "table", ",", "$", "foreignKey", ",", "$", "otherKey", ",", "$", "relation", ",", "$", "fieldId", ")", ";", "// add constraints", "$", "belongsToMany", "->", "wherePivot", "(", "config", "(", "'pxlcms.relations.references.keys.field'", ",", "'from_field_id'", ")", ",", "$", "fieldId", ")", ";", "return", "$", "belongsToMany", ";", "}" ]
Override for special cms_m_references 'pivot' table @param string $related @param string $table @param string $foreignKey @param string $otherKey @param string $relation @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
[ "Override", "for", "special", "cms_m_references", "pivot", "table" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L412-L449
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.belongsToManyNormal
public function belongsToManyNormal($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null) { return parent::belongsToMany($related, $table, $foreignKey, $otherKey, $relation); }
php
public function belongsToManyNormal($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null) { return parent::belongsToMany($related, $table, $foreignKey, $otherKey, $relation); }
[ "public", "function", "belongsToManyNormal", "(", "$", "related", ",", "$", "table", "=", "null", ",", "$", "foreignKey", "=", "null", ",", "$", "otherKey", "=", "null", ",", "$", "relation", "=", "null", ")", "{", "return", "parent", "::", "belongsToMany", "(", "$", "related", ",", "$", "table", ",", "$", "foreignKey", ",", "$", "otherKey", ",", "$", "relation", ")", ";", "}" ]
For when you still want to use the 'normal' belongsToMany relationship in a CmsModel that should be related to non-CmsModels in the laravel convention @param string $related @param string $table @param string $foreignKey @param string $otherKey @param string $relation @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
[ "For", "when", "you", "still", "want", "to", "use", "the", "normal", "belongsToMany", "relationship", "in", "a", "CmsModel", "that", "should", "be", "related", "to", "non", "-", "CmsModels", "in", "the", "laravel", "convention" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L462-L465
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.hasOne
public function hasOne($related, $foreignKey = null, $localKey = null, $locale = null) { $relation = $this->getHasOneOrManyCaller(); if ( ! ($specialType = $this->getCmsSpecialRelationType($relation))) { return parent::hasOne($related, $foreignKey, $localKey); } list($foreignKey, $fieldKey) = $this->getKeysForSpecialRelation($specialType, $foreignKey); $fieldId = $this->getCmsReferenceFieldId($relation); // create the correct hasOne, for special relations that must save field_id values /** @var Builder $hasOne */ if ( $specialType === static::RELATION_TYPE_CHECKBOX || $specialType === static::RELATION_TYPE_FILE || $specialType === static::RELATION_TYPE_IMAGE ) { /** @var Model $instance */ $instance = new $related; $localKey = $localKey ?: $this->getKeyName(); $hasOne = new HasOne( $instance->newQuery(), $this, $instance->getTable() . '.' . $foreignKey, $localKey, $fieldId, $specialType ); } else { $hasOne = parent::hasOne($related, $foreignKey, $localKey); } // add field key for wheres $hasOne->where($fieldKey, $fieldId); // limit to selected locale, if translated if ($this->getCmsSpecialRelationTranslated($relation)) { if (is_null($locale)) $locale = app()->getLocale(); $hasOne->where( config('pxlcms.translatable.locale_key'), $this->lookUpLanguageIdForLocale($locale) ); } return $hasOne; }
php
public function hasOne($related, $foreignKey = null, $localKey = null, $locale = null) { $relation = $this->getHasOneOrManyCaller(); if ( ! ($specialType = $this->getCmsSpecialRelationType($relation))) { return parent::hasOne($related, $foreignKey, $localKey); } list($foreignKey, $fieldKey) = $this->getKeysForSpecialRelation($specialType, $foreignKey); $fieldId = $this->getCmsReferenceFieldId($relation); // create the correct hasOne, for special relations that must save field_id values /** @var Builder $hasOne */ if ( $specialType === static::RELATION_TYPE_CHECKBOX || $specialType === static::RELATION_TYPE_FILE || $specialType === static::RELATION_TYPE_IMAGE ) { /** @var Model $instance */ $instance = new $related; $localKey = $localKey ?: $this->getKeyName(); $hasOne = new HasOne( $instance->newQuery(), $this, $instance->getTable() . '.' . $foreignKey, $localKey, $fieldId, $specialType ); } else { $hasOne = parent::hasOne($related, $foreignKey, $localKey); } // add field key for wheres $hasOne->where($fieldKey, $fieldId); // limit to selected locale, if translated if ($this->getCmsSpecialRelationTranslated($relation)) { if (is_null($locale)) $locale = app()->getLocale(); $hasOne->where( config('pxlcms.translatable.locale_key'), $this->lookUpLanguageIdForLocale($locale) ); } return $hasOne; }
[ "public", "function", "hasOne", "(", "$", "related", ",", "$", "foreignKey", "=", "null", ",", "$", "localKey", "=", "null", ",", "$", "locale", "=", "null", ")", "{", "$", "relation", "=", "$", "this", "->", "getHasOneOrManyCaller", "(", ")", ";", "if", "(", "!", "(", "$", "specialType", "=", "$", "this", "->", "getCmsSpecialRelationType", "(", "$", "relation", ")", ")", ")", "{", "return", "parent", "::", "hasOne", "(", "$", "related", ",", "$", "foreignKey", ",", "$", "localKey", ")", ";", "}", "list", "(", "$", "foreignKey", ",", "$", "fieldKey", ")", "=", "$", "this", "->", "getKeysForSpecialRelation", "(", "$", "specialType", ",", "$", "foreignKey", ")", ";", "$", "fieldId", "=", "$", "this", "->", "getCmsReferenceFieldId", "(", "$", "relation", ")", ";", "// create the correct hasOne, for special relations that must save field_id values", "/** @var Builder $hasOne */", "if", "(", "$", "specialType", "===", "static", "::", "RELATION_TYPE_CHECKBOX", "||", "$", "specialType", "===", "static", "::", "RELATION_TYPE_FILE", "||", "$", "specialType", "===", "static", "::", "RELATION_TYPE_IMAGE", ")", "{", "/** @var Model $instance */", "$", "instance", "=", "new", "$", "related", ";", "$", "localKey", "=", "$", "localKey", "?", ":", "$", "this", "->", "getKeyName", "(", ")", ";", "$", "hasOne", "=", "new", "HasOne", "(", "$", "instance", "->", "newQuery", "(", ")", ",", "$", "this", ",", "$", "instance", "->", "getTable", "(", ")", ".", "'.'", ".", "$", "foreignKey", ",", "$", "localKey", ",", "$", "fieldId", ",", "$", "specialType", ")", ";", "}", "else", "{", "$", "hasOne", "=", "parent", "::", "hasOne", "(", "$", "related", ",", "$", "foreignKey", ",", "$", "localKey", ")", ";", "}", "// add field key for wheres", "$", "hasOne", "->", "where", "(", "$", "fieldKey", ",", "$", "fieldId", ")", ";", "// limit to selected locale, if translated", "if", "(", "$", "this", "->", "getCmsSpecialRelationTranslated", "(", "$", "relation", ")", ")", "{", "if", "(", "is_null", "(", "$", "locale", ")", ")", "$", "locale", "=", "app", "(", ")", "->", "getLocale", "(", ")", ";", "$", "hasOne", "->", "where", "(", "config", "(", "'pxlcms.translatable.locale_key'", ")", ",", "$", "this", "->", "lookUpLanguageIdForLocale", "(", "$", "locale", ")", ")", ";", "}", "return", "$", "hasOne", ";", "}" ]
Overridden to catch special relationships to standard CMS models @param string $related @param string $foreignKey @param string $localKey @param string $locale only used as an override, and only for ML images @return \Illuminate\Database\Eloquent\Relations\HasOne
[ "Overridden", "to", "catch", "special", "relationships", "to", "standard", "CMS", "models" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L537-L589
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getHasOneOrManyCaller
protected function getHasOneOrManyCaller() { $self = __FUNCTION__; $caller = Arr::first(debug_backtrace(false), function ($key, $trace) use ($self) { $caller = $trace['function']; return ! in_array($caller, CmsModel::$hasRelationMethods) && $caller != $self; }); return ! is_null($caller) ? $caller['function'] : null; }
php
protected function getHasOneOrManyCaller() { $self = __FUNCTION__; $caller = Arr::first(debug_backtrace(false), function ($key, $trace) use ($self) { $caller = $trace['function']; return ! in_array($caller, CmsModel::$hasRelationMethods) && $caller != $self; }); return ! is_null($caller) ? $caller['function'] : null; }
[ "protected", "function", "getHasOneOrManyCaller", "(", ")", "{", "$", "self", "=", "__FUNCTION__", ";", "$", "caller", "=", "Arr", "::", "first", "(", "debug_backtrace", "(", "false", ")", ",", "function", "(", "$", "key", ",", "$", "trace", ")", "use", "(", "$", "self", ")", "{", "$", "caller", "=", "$", "trace", "[", "'function'", "]", ";", "return", "!", "in_array", "(", "$", "caller", ",", "CmsModel", "::", "$", "hasRelationMethods", ")", "&&", "$", "caller", "!=", "$", "self", ";", "}", ")", ";", "return", "!", "is_null", "(", "$", "caller", ")", "?", "$", "caller", "[", "'function'", "]", ":", "null", ";", "}" ]
Get the relationship name of the has one/many @return string
[ "Get", "the", "relationship", "name", "of", "the", "has", "one", "/", "many" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L596-L607
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getKeysForSpecialRelation
protected function getKeysForSpecialRelation($specialType, $foreignKey = null) { switch ($specialType) { case static::RELATION_TYPE_FILE: $foreignKey = $foreignKey ?: config('pxlcms.relations.files.keys.entry'); $secondaryKey = config('pxlcms.relations.files.keys.field'); break; case static::RELATION_TYPE_CHECKBOX: $foreignKey = $foreignKey ?: config('pxlcms.relations.checkboxes.keys.entry'); $secondaryKey = config('pxlcms.relations.checkboxes.keys.field'); break; case static::RELATION_TYPE_IMAGE: default: $foreignKey = $foreignKey ?: config('pxlcms.relations.images.keys.entry'); $secondaryKey = config('pxlcms.relations.images.keys.field'); } return [ $foreignKey, $secondaryKey ]; }
php
protected function getKeysForSpecialRelation($specialType, $foreignKey = null) { switch ($specialType) { case static::RELATION_TYPE_FILE: $foreignKey = $foreignKey ?: config('pxlcms.relations.files.keys.entry'); $secondaryKey = config('pxlcms.relations.files.keys.field'); break; case static::RELATION_TYPE_CHECKBOX: $foreignKey = $foreignKey ?: config('pxlcms.relations.checkboxes.keys.entry'); $secondaryKey = config('pxlcms.relations.checkboxes.keys.field'); break; case static::RELATION_TYPE_IMAGE: default: $foreignKey = $foreignKey ?: config('pxlcms.relations.images.keys.entry'); $secondaryKey = config('pxlcms.relations.images.keys.field'); } return [ $foreignKey, $secondaryKey ]; }
[ "protected", "function", "getKeysForSpecialRelation", "(", "$", "specialType", ",", "$", "foreignKey", "=", "null", ")", "{", "switch", "(", "$", "specialType", ")", "{", "case", "static", "::", "RELATION_TYPE_FILE", ":", "$", "foreignKey", "=", "$", "foreignKey", "?", ":", "config", "(", "'pxlcms.relations.files.keys.entry'", ")", ";", "$", "secondaryKey", "=", "config", "(", "'pxlcms.relations.files.keys.field'", ")", ";", "break", ";", "case", "static", "::", "RELATION_TYPE_CHECKBOX", ":", "$", "foreignKey", "=", "$", "foreignKey", "?", ":", "config", "(", "'pxlcms.relations.checkboxes.keys.entry'", ")", ";", "$", "secondaryKey", "=", "config", "(", "'pxlcms.relations.checkboxes.keys.field'", ")", ";", "break", ";", "case", "static", "::", "RELATION_TYPE_IMAGE", ":", "default", ":", "$", "foreignKey", "=", "$", "foreignKey", "?", ":", "config", "(", "'pxlcms.relations.images.keys.entry'", ")", ";", "$", "secondaryKey", "=", "config", "(", "'pxlcms.relations.images.keys.field'", ")", ";", "}", "return", "[", "$", "foreignKey", ",", "$", "secondaryKey", "]", ";", "}" ]
Get the foreign and field keys for the special relation's standard CMS model @param int $specialType @param string $foreignKey @return array [ foreignKey, secondaryKey ]
[ "Get", "the", "foreign", "and", "field", "keys", "for", "the", "special", "relation", "s", "standard", "CMS", "model" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L616-L637
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getBelongsToRelationAttributeValue
public function getBelongsToRelationAttributeValue($key) { $relationKey = camel_case($key); $attributeKey = snake_case($key); if ($this->relationLoaded($relationKey)) { // check to make sure we don't break eager loading and internal // lookups for the foreign key $self = __FUNCTION__; $caller = array_first(debug_backtrace(false), function ($key, $trace) use ($self) { $caller = $trace['function']; // skip first two (since that includes the Model's generated method) if ($key < 2) { return false; } if (array_get($trace, 'class') === 'Illuminate\Database\Eloquent\Relations\BelongsTo') { return false; } return $caller != $self && $caller != 'mutateAttribute' && $caller != 'getAttributeValue' && $caller != 'getAttribute' && $caller != '__get'; }); if ( ! array_key_exists('class', $caller) || ( $caller['class'] !== 'Illuminate\Database\Eloquent\Model' && $caller['class'] !== 'Illuminate\Database\Eloquent\Builder' && $caller['class'] !== 'Illuminate\Database\Eloquent\Relations\Relation' ) ) { return $this->relations[$relationKey]; } } return $this->attributes[$attributeKey]; }
php
public function getBelongsToRelationAttributeValue($key) { $relationKey = camel_case($key); $attributeKey = snake_case($key); if ($this->relationLoaded($relationKey)) { // check to make sure we don't break eager loading and internal // lookups for the foreign key $self = __FUNCTION__; $caller = array_first(debug_backtrace(false), function ($key, $trace) use ($self) { $caller = $trace['function']; // skip first two (since that includes the Model's generated method) if ($key < 2) { return false; } if (array_get($trace, 'class') === 'Illuminate\Database\Eloquent\Relations\BelongsTo') { return false; } return $caller != $self && $caller != 'mutateAttribute' && $caller != 'getAttributeValue' && $caller != 'getAttribute' && $caller != '__get'; }); if ( ! array_key_exists('class', $caller) || ( $caller['class'] !== 'Illuminate\Database\Eloquent\Model' && $caller['class'] !== 'Illuminate\Database\Eloquent\Builder' && $caller['class'] !== 'Illuminate\Database\Eloquent\Relations\Relation' ) ) { return $this->relations[$relationKey]; } } return $this->attributes[$attributeKey]; }
[ "public", "function", "getBelongsToRelationAttributeValue", "(", "$", "key", ")", "{", "$", "relationKey", "=", "camel_case", "(", "$", "key", ")", ";", "$", "attributeKey", "=", "snake_case", "(", "$", "key", ")", ";", "if", "(", "$", "this", "->", "relationLoaded", "(", "$", "relationKey", ")", ")", "{", "// check to make sure we don't break eager loading and internal", "// lookups for the foreign key", "$", "self", "=", "__FUNCTION__", ";", "$", "caller", "=", "array_first", "(", "debug_backtrace", "(", "false", ")", ",", "function", "(", "$", "key", ",", "$", "trace", ")", "use", "(", "$", "self", ")", "{", "$", "caller", "=", "$", "trace", "[", "'function'", "]", ";", "// skip first two (since that includes the Model's generated method)", "if", "(", "$", "key", "<", "2", ")", "{", "return", "false", ";", "}", "if", "(", "array_get", "(", "$", "trace", ",", "'class'", ")", "===", "'Illuminate\\Database\\Eloquent\\Relations\\BelongsTo'", ")", "{", "return", "false", ";", "}", "return", "$", "caller", "!=", "$", "self", "&&", "$", "caller", "!=", "'mutateAttribute'", "&&", "$", "caller", "!=", "'getAttributeValue'", "&&", "$", "caller", "!=", "'getAttribute'", "&&", "$", "caller", "!=", "'__get'", ";", "}", ")", ";", "if", "(", "!", "array_key_exists", "(", "'class'", ",", "$", "caller", ")", "||", "(", "$", "caller", "[", "'class'", "]", "!==", "'Illuminate\\Database\\Eloquent\\Model'", "&&", "$", "caller", "[", "'class'", "]", "!==", "'Illuminate\\Database\\Eloquent\\Builder'", "&&", "$", "caller", "[", "'class'", "]", "!==", "'Illuminate\\Database\\Eloquent\\Relations\\Relation'", ")", ")", "{", "return", "$", "this", "->", "relations", "[", "$", "relationKey", "]", ";", "}", "}", "return", "$", "this", "->", "attributes", "[", "$", "attributeKey", "]", ";", "}" ]
Returns value for either foreign key or eager loaded contents of relation, depending on what is expected This should not break calls to the belongsTo relation method, including after using the load() method to eager load the relation's contents @param string $key @return mixed
[ "Returns", "value", "for", "either", "foreign", "key", "or", "eager", "loaded", "contents", "of", "relation", "depending", "on", "what", "is", "expected" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L649-L690
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.updateTimestamps
protected function updateTimestamps() { $time = $this->freshTimestamp(); if (! $this->isDirty($this->updatedAtColumn)) { $this->setUpdatedAt($time); } if (! $this->exists && ! $this->isDirty($this->createdAtColumn)) { $this->setCreatedAt($time); } }
php
protected function updateTimestamps() { $time = $this->freshTimestamp(); if (! $this->isDirty($this->updatedAtColumn)) { $this->setUpdatedAt($time); } if (! $this->exists && ! $this->isDirty($this->createdAtColumn)) { $this->setCreatedAt($time); } }
[ "protected", "function", "updateTimestamps", "(", ")", "{", "$", "time", "=", "$", "this", "->", "freshTimestamp", "(", ")", ";", "if", "(", "!", "$", "this", "->", "isDirty", "(", "$", "this", "->", "updatedAtColumn", ")", ")", "{", "$", "this", "->", "setUpdatedAt", "(", "$", "time", ")", ";", "}", "if", "(", "!", "$", "this", "->", "exists", "&&", "!", "$", "this", "->", "isDirty", "(", "$", "this", "->", "createdAtColumn", ")", ")", "{", "$", "this", "->", "setCreatedAt", "(", "$", "time", ")", ";", "}", "}" ]
Update the creation and update timestamps. @return void
[ "Update", "the", "creation", "and", "update", "timestamps", "." ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L701-L712
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getImagesWithResizes
protected function getImagesWithResizes() { // first get the images through the relation $relation = $this->getRelationForImagesWithResizesCaller(); $images = $this->{$relation}()->get(); if (empty($images)) return $images; // then get extra info and retrieve the resizes for it $fieldId = $this->getCmsReferenceFieldId($relation); $resizes = $this->getResizesForFieldId($fieldId); if (empty($resizes)) return $images; // decorate the images with resizes foreach ($images as $image) { $fileName = $image->file; $imageResizes = []; foreach ($resizes as $resize) { $imageResizes[ $resize->prefix ] = [ 'id' => $resize->id, 'prefix' => $resize->prefix, 'file' => $resize->prefix . $fileName, 'url' => Paths::images($resize->prefix . $fileName), 'width' => $resize->width, 'height' => $resize->height, ]; } // append full resizes info $image->resizes = $imageResizes; } return $images; }
php
protected function getImagesWithResizes() { // first get the images through the relation $relation = $this->getRelationForImagesWithResizesCaller(); $images = $this->{$relation}()->get(); if (empty($images)) return $images; // then get extra info and retrieve the resizes for it $fieldId = $this->getCmsReferenceFieldId($relation); $resizes = $this->getResizesForFieldId($fieldId); if (empty($resizes)) return $images; // decorate the images with resizes foreach ($images as $image) { $fileName = $image->file; $imageResizes = []; foreach ($resizes as $resize) { $imageResizes[ $resize->prefix ] = [ 'id' => $resize->id, 'prefix' => $resize->prefix, 'file' => $resize->prefix . $fileName, 'url' => Paths::images($resize->prefix . $fileName), 'width' => $resize->width, 'height' => $resize->height, ]; } // append full resizes info $image->resizes = $imageResizes; } return $images; }
[ "protected", "function", "getImagesWithResizes", "(", ")", "{", "// first get the images through the relation", "$", "relation", "=", "$", "this", "->", "getRelationForImagesWithResizesCaller", "(", ")", ";", "$", "images", "=", "$", "this", "->", "{", "$", "relation", "}", "(", ")", "->", "get", "(", ")", ";", "if", "(", "empty", "(", "$", "images", ")", ")", "return", "$", "images", ";", "// then get extra info and retrieve the resizes for it", "$", "fieldId", "=", "$", "this", "->", "getCmsReferenceFieldId", "(", "$", "relation", ")", ";", "$", "resizes", "=", "$", "this", "->", "getResizesForFieldId", "(", "$", "fieldId", ")", ";", "if", "(", "empty", "(", "$", "resizes", ")", ")", "return", "$", "images", ";", "// decorate the images with resizes", "foreach", "(", "$", "images", "as", "$", "image", ")", "{", "$", "fileName", "=", "$", "image", "->", "file", ";", "$", "imageResizes", "=", "[", "]", ";", "foreach", "(", "$", "resizes", "as", "$", "resize", ")", "{", "$", "imageResizes", "[", "$", "resize", "->", "prefix", "]", "=", "[", "'id'", "=>", "$", "resize", "->", "id", ",", "'prefix'", "=>", "$", "resize", "->", "prefix", ",", "'file'", "=>", "$", "resize", "->", "prefix", ".", "$", "fileName", ",", "'url'", "=>", "Paths", "::", "images", "(", "$", "resize", "->", "prefix", ".", "$", "fileName", ")", ",", "'width'", "=>", "$", "resize", "->", "width", ",", "'height'", "=>", "$", "resize", "->", "height", ",", "]", ";", "}", "// append full resizes info", "$", "image", "->", "resizes", "=", "$", "imageResizes", ";", "}", "return", "$", "images", ";", "}" ]
Returns resize-enriched images for a special CMS model image relation To be called from an accessor, so it can return images based on its name, which should be get<relationname>Attribute(). @return Collection
[ "Returns", "resize", "-", "enriched", "images", "for", "a", "special", "CMS", "model", "image", "relation" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L772-L811
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.getRelationForImagesWithResizesCaller
protected function getRelationForImagesWithResizesCaller() { $self = __FUNCTION__; $caller = Arr::first(debug_backtrace(false), function ($key, $trace) use ($self) { $caller = $trace['function']; return ! in_array($caller, ['getImagesWithResizes']) && $caller != $self; }); if (is_null($caller)) return null; // strip 'get' from front and 'attribute' from rear return Str::camel(substr($caller['function'], 3, -9)); }
php
protected function getRelationForImagesWithResizesCaller() { $self = __FUNCTION__; $caller = Arr::first(debug_backtrace(false), function ($key, $trace) use ($self) { $caller = $trace['function']; return ! in_array($caller, ['getImagesWithResizes']) && $caller != $self; }); if (is_null($caller)) return null; // strip 'get' from front and 'attribute' from rear return Str::camel(substr($caller['function'], 3, -9)); }
[ "protected", "function", "getRelationForImagesWithResizesCaller", "(", ")", "{", "$", "self", "=", "__FUNCTION__", ";", "$", "caller", "=", "Arr", "::", "first", "(", "debug_backtrace", "(", "false", ")", ",", "function", "(", "$", "key", ",", "$", "trace", ")", "use", "(", "$", "self", ")", "{", "$", "caller", "=", "$", "trace", "[", "'function'", "]", ";", "return", "!", "in_array", "(", "$", "caller", ",", "[", "'getImagesWithResizes'", "]", ")", "&&", "$", "caller", "!=", "$", "self", ";", "}", ")", ";", "if", "(", "is_null", "(", "$", "caller", ")", ")", "return", "null", ";", "// strip 'get' from front and 'attribute' from rear", "return", "Str", "::", "camel", "(", "substr", "(", "$", "caller", "[", "'function'", "]", ",", "3", ",", "-", "9", ")", ")", ";", "}" ]
Get the relationship name of the image accessor for which images are enriched @return string
[ "Get", "the", "relationship", "name", "of", "the", "image", "accessor", "for", "which", "images", "are", "enriched" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L836-L850
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.lookUpLanguageIdForLocale
public function lookUpLanguageIdForLocale($locale) { $locale = $this->normalizeLocale($locale); /** @var Model $languageModel */ $languageModel = static::$cmsLanguageModel; $language = $languageModel::where(config('pxlcms.translatable.locale_code_column'), $locale) ->remember((config('pxlcms.cache.languages', 15))) ->first(); if (empty($language)) return null; return $language->id; }
php
public function lookUpLanguageIdForLocale($locale) { $locale = $this->normalizeLocale($locale); /** @var Model $languageModel */ $languageModel = static::$cmsLanguageModel; $language = $languageModel::where(config('pxlcms.translatable.locale_code_column'), $locale) ->remember((config('pxlcms.cache.languages', 15))) ->first(); if (empty($language)) return null; return $language->id; }
[ "public", "function", "lookUpLanguageIdForLocale", "(", "$", "locale", ")", "{", "$", "locale", "=", "$", "this", "->", "normalizeLocale", "(", "$", "locale", ")", ";", "/** @var Model $languageModel */", "$", "languageModel", "=", "static", "::", "$", "cmsLanguageModel", ";", "$", "language", "=", "$", "languageModel", "::", "where", "(", "config", "(", "'pxlcms.translatable.locale_code_column'", ")", ",", "$", "locale", ")", "->", "remember", "(", "(", "config", "(", "'pxlcms.cache.languages'", ",", "15", ")", ")", ")", "->", "first", "(", ")", ";", "if", "(", "empty", "(", "$", "language", ")", ")", "return", "null", ";", "return", "$", "language", "->", "id", ";", "}" ]
Retrieves (and caches) the locale @param string $locale @return int|null null if language was not found for locale
[ "Retrieves", "(", "and", "caches", ")", "the", "locale" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L863-L877
czim/laravel-pxlcms
src/Models/CmsModel.php
CmsModel.lookupLocaleForLanguageId
public function lookupLocaleForLanguageId($languageId) { /** @var Model $languageModel */ $languageModel = static::$cmsLanguageModel; $language = $languageModel::where('id', $languageId) ->remember((config('pxlcms.cache.languages', 15))) ->first(); if (empty($language)) return null; return $this->normalizeToLocale($language->code); }
php
public function lookupLocaleForLanguageId($languageId) { /** @var Model $languageModel */ $languageModel = static::$cmsLanguageModel; $language = $languageModel::where('id', $languageId) ->remember((config('pxlcms.cache.languages', 15))) ->first(); if (empty($language)) return null; return $this->normalizeToLocale($language->code); }
[ "public", "function", "lookupLocaleForLanguageId", "(", "$", "languageId", ")", "{", "/** @var Model $languageModel */", "$", "languageModel", "=", "static", "::", "$", "cmsLanguageModel", ";", "$", "language", "=", "$", "languageModel", "::", "where", "(", "'id'", ",", "$", "languageId", ")", "->", "remember", "(", "(", "config", "(", "'pxlcms.cache.languages'", ",", "15", ")", ")", ")", "->", "first", "(", ")", ";", "if", "(", "empty", "(", "$", "language", ")", ")", "return", "null", ";", "return", "$", "this", "->", "normalizeToLocale", "(", "$", "language", "->", "code", ")", ";", "}" ]
Retrieves locale for a given language ID code @param int $languageId @return string|null of language for ID was not found
[ "Retrieves", "locale", "for", "a", "given", "language", "ID", "code" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/CmsModel.php#L885-L897
refinery29/piston
src/CookieJar.php
CookieJar.get
public function get($key) { Assertion::string($key); if (!\array_key_exists($key, $this->cookies)) { return; } return $this->cookies[$key]; }
php
public function get($key) { Assertion::string($key); if (!\array_key_exists($key, $this->cookies)) { return; } return $this->cookies[$key]; }
[ "public", "function", "get", "(", "$", "key", ")", "{", "Assertion", "::", "string", "(", "$", "key", ")", ";", "if", "(", "!", "\\", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "cookies", ")", ")", "{", "return", ";", "}", "return", "$", "this", "->", "cookies", "[", "$", "key", "]", ";", "}" ]
@param string $key @return mixed
[ "@param", "string", "$key" ]
train
https://github.com/refinery29/piston/blob/75c402e814136577fa9a02479e8803aca664c865/src/CookieJar.php#L36-L45
harp-orm/query
src/DB.php
DB.execute
public function execute($sql, array $parameters = array()) { $this->logger->info($sql, array('parameters' => $parameters)); try { $statement = $this->getPdo()->prepare($sql); $statement->execute($parameters); } catch (PDOException $exception) { $this->logger->error($exception->getMessage()); throw $exception; } return $statement; }
php
public function execute($sql, array $parameters = array()) { $this->logger->info($sql, array('parameters' => $parameters)); try { $statement = $this->getPdo()->prepare($sql); $statement->execute($parameters); } catch (PDOException $exception) { $this->logger->error($exception->getMessage()); throw $exception; } return $statement; }
[ "public", "function", "execute", "(", "$", "sql", ",", "array", "$", "parameters", "=", "array", "(", ")", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "$", "sql", ",", "array", "(", "'parameters'", "=>", "$", "parameters", ")", ")", ";", "try", "{", "$", "statement", "=", "$", "this", "->", "getPdo", "(", ")", "->", "prepare", "(", "$", "sql", ")", ";", "$", "statement", "->", "execute", "(", "$", "parameters", ")", ";", "}", "catch", "(", "PDOException", "$", "exception", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "$", "exception", "->", "getMessage", "(", ")", ")", ";", "throw", "$", "exception", ";", "}", "return", "$", "statement", ";", "}" ]
Run "prepare" a statement and then execute it @param string $sql @param array $parameters @return \PDOStatement
[ "Run", "prepare", "a", "statement", "and", "then", "execute", "it" ]
train
https://github.com/harp-orm/query/blob/98ce2468a0a31fe15ed3692bad32547bf6dbe41a/src/DB.php#L240-L254
Elendev/ElendevRoxyFilemanBundle
DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('elendev_roxy_fileman'); $rootNode ->children() ->arrayNode('profiles') ->useAttributeAsKey('name') ->prototype('array') ->children() ->scalarNode('file_system_service_id')->defaultNull()->end() ->append($this->createLocalFilesystem()) ->append($this->createConf()) ->end() ->end() ->end() ->scalarNode('roxyfileman_lib_path') ->defaultNull() ->end() ->scalarNode('file_system_service_id') ->defaultNull() ->end() ->append($this->createLocalFilesystem()) ->append($this->createConf()) ->end(); return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('elendev_roxy_fileman'); $rootNode ->children() ->arrayNode('profiles') ->useAttributeAsKey('name') ->prototype('array') ->children() ->scalarNode('file_system_service_id')->defaultNull()->end() ->append($this->createLocalFilesystem()) ->append($this->createConf()) ->end() ->end() ->end() ->scalarNode('roxyfileman_lib_path') ->defaultNull() ->end() ->scalarNode('file_system_service_id') ->defaultNull() ->end() ->append($this->createLocalFilesystem()) ->append($this->createConf()) ->end(); return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "rootNode", "=", "$", "treeBuilder", "->", "root", "(", "'elendev_roxy_fileman'", ")", ";", "$", "rootNode", "->", "children", "(", ")", "->", "arrayNode", "(", "'profiles'", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "prototype", "(", "'array'", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'file_system_service_id'", ")", "->", "defaultNull", "(", ")", "->", "end", "(", ")", "->", "append", "(", "$", "this", "->", "createLocalFilesystem", "(", ")", ")", "->", "append", "(", "$", "this", "->", "createConf", "(", ")", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'roxyfileman_lib_path'", ")", "->", "defaultNull", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'file_system_service_id'", ")", "->", "defaultNull", "(", ")", "->", "end", "(", ")", "->", "append", "(", "$", "this", "->", "createLocalFilesystem", "(", ")", ")", "->", "append", "(", "$", "this", "->", "createConf", "(", ")", ")", "->", "end", "(", ")", ";", "return", "$", "treeBuilder", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/Elendev/ElendevRoxyFilemanBundle/blob/2173ce00e4f1d22960eec70b437a5908f4681dc1/DependencyInjection/Configuration.php#L27-L55
tequila/mongodb-php-lib
src/CommandExecutor.php
CommandExecutor.getResolver
private function getResolver(array $command) { $commandName = key($command); if (!isset(self::$resolverClassesByCommandName[$commandName])) { throw new LogicException( sprintf('OptionsResolver for command "%s" does not exist.', $commandName) ); } $resolverClass = self::$resolverClassesByCommandName[$commandName]; return OptionsResolver::get($resolverClass); }
php
private function getResolver(array $command) { $commandName = key($command); if (!isset(self::$resolverClassesByCommandName[$commandName])) { throw new LogicException( sprintf('OptionsResolver for command "%s" does not exist.', $commandName) ); } $resolverClass = self::$resolverClassesByCommandName[$commandName]; return OptionsResolver::get($resolverClass); }
[ "private", "function", "getResolver", "(", "array", "$", "command", ")", "{", "$", "commandName", "=", "key", "(", "$", "command", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "resolverClassesByCommandName", "[", "$", "commandName", "]", ")", ")", "{", "throw", "new", "LogicException", "(", "sprintf", "(", "'OptionsResolver for command \"%s\" does not exist.'", ",", "$", "commandName", ")", ")", ";", "}", "$", "resolverClass", "=", "self", "::", "$", "resolverClassesByCommandName", "[", "$", "commandName", "]", ";", "return", "OptionsResolver", "::", "get", "(", "$", "resolverClass", ")", ";", "}" ]
@param array $command @return OptionsResolver
[ "@param", "array", "$command" ]
train
https://github.com/tequila/mongodb-php-lib/blob/49a25f45268df358f5ceb40a655d9a7ddc6db4f7/src/CommandExecutor.php#L127-L139
yishixincheng/Xl_WeApp_SDK
src/Lib/WxPayParam.php
WxPayParam.makeSign
public function makeSign() { //签名步骤一:按字典序排序参数 ksort($this->values); $string = $this->ToUrlParams(); //签名步骤二:在string后加入KEY $string = $string . "&key=".Config::getKEY(); //签名步骤三:MD5加密 $string = md5($string); //签名步骤四:所有字符转为大写 $result = strtoupper($string); return $result; }
php
public function makeSign() { //签名步骤一:按字典序排序参数 ksort($this->values); $string = $this->ToUrlParams(); //签名步骤二:在string后加入KEY $string = $string . "&key=".Config::getKEY(); //签名步骤三:MD5加密 $string = md5($string); //签名步骤四:所有字符转为大写 $result = strtoupper($string); return $result; }
[ "public", "function", "makeSign", "(", ")", "{", "//签名步骤一:按字典序排序参数", "ksort", "(", "$", "this", "->", "values", ")", ";", "$", "string", "=", "$", "this", "->", "ToUrlParams", "(", ")", ";", "//签名步骤二:在string后加入KEY", "$", "string", "=", "$", "string", ".", "\"&key=\"", ".", "Config", "::", "getKEY", "(", ")", ";", "//签名步骤三:MD5加密", "$", "string", "=", "md5", "(", "$", "string", ")", ";", "//签名步骤四:所有字符转为大写", "$", "result", "=", "strtoupper", "(", "$", "string", ")", ";", "return", "$", "result", ";", "}" ]
生成签名 @return 签名,本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
[ "生成签名" ]
train
https://github.com/yishixincheng/Xl_WeApp_SDK/blob/26e58154e2aceccd6ffb92c4ed2b1c5a0b6414da/src/Lib/WxPayParam.php#L108-L120
yishixincheng/Xl_WeApp_SDK
src/Lib/WxPayParam.php
WxPayResult.Init
public static function Init($xml) { $obj = new self(); $obj->FromXml($xml); //fix bug 2015-06-29 if($obj->values['return_code'] != 'SUCCESS'){ return $obj->GetValues(); } $obj->CheckSign(); return $obj->GetValues(); }
php
public static function Init($xml) { $obj = new self(); $obj->FromXml($xml); //fix bug 2015-06-29 if($obj->values['return_code'] != 'SUCCESS'){ return $obj->GetValues(); } $obj->CheckSign(); return $obj->GetValues(); }
[ "public", "static", "function", "Init", "(", "$", "xml", ")", "{", "$", "obj", "=", "new", "self", "(", ")", ";", "$", "obj", "->", "FromXml", "(", "$", "xml", ")", ";", "//fix bug 2015-06-29", "if", "(", "$", "obj", "->", "values", "[", "'return_code'", "]", "!=", "'SUCCESS'", ")", "{", "return", "$", "obj", "->", "GetValues", "(", ")", ";", "}", "$", "obj", "->", "CheckSign", "(", ")", ";", "return", "$", "obj", "->", "GetValues", "(", ")", ";", "}" ]
将xml转为array @param string $xml @throws WxPayException
[ "将xml转为array" ]
train
https://github.com/yishixincheng/Xl_WeApp_SDK/blob/26e58154e2aceccd6ffb92c4ed2b1c5a0b6414da/src/Lib/WxPayParam.php#L230-L240
WellCommerce/OrderBundle
Form/Front/CartFormBuilder.php
CartFormBuilder.addShippingOptions
private function addShippingOptions(Order $order, FormInterface $form) { if ($order->getShippingMethod() instanceof ShippingMethod) { $provider = $this->getOptionsProvider($order->getShippingMethod()); if ($provider instanceof ShippingMethodOptionsProviderInterface) { $form->addChild($this->getElement('select', [ 'name' => 'shippingMethodOption', 'label' => 'order.label.shipping_method', 'options' => $provider->getShippingOptions(), ])); } } }
php
private function addShippingOptions(Order $order, FormInterface $form) { if ($order->getShippingMethod() instanceof ShippingMethod) { $provider = $this->getOptionsProvider($order->getShippingMethod()); if ($provider instanceof ShippingMethodOptionsProviderInterface) { $form->addChild($this->getElement('select', [ 'name' => 'shippingMethodOption', 'label' => 'order.label.shipping_method', 'options' => $provider->getShippingOptions(), ])); } } }
[ "private", "function", "addShippingOptions", "(", "Order", "$", "order", ",", "FormInterface", "$", "form", ")", "{", "if", "(", "$", "order", "->", "getShippingMethod", "(", ")", "instanceof", "ShippingMethod", ")", "{", "$", "provider", "=", "$", "this", "->", "getOptionsProvider", "(", "$", "order", "->", "getShippingMethod", "(", ")", ")", ";", "if", "(", "$", "provider", "instanceof", "ShippingMethodOptionsProviderInterface", ")", "{", "$", "form", "->", "addChild", "(", "$", "this", "->", "getElement", "(", "'select'", ",", "[", "'name'", "=>", "'shippingMethodOption'", ",", "'label'", "=>", "'order.label.shipping_method'", ",", "'options'", "=>", "$", "provider", "->", "getShippingOptions", "(", ")", ",", "]", ")", ")", ";", "}", "}", "}" ]
Adds shipping options if available for order's shipping method @param Order $order @param FormInterface $form
[ "Adds", "shipping", "options", "if", "available", "for", "order", "s", "shipping", "method" ]
train
https://github.com/WellCommerce/OrderBundle/blob/d72cfb51eab7a1f66f186900d1e2d533a822c424/Form/Front/CartFormBuilder.php#L85-L97
WellCommerce/OrderBundle
Form/Front/CartFormBuilder.php
CartFormBuilder.addPaymentMethods
private function addPaymentMethods(Order $order, ElementInterface $radioGroup) { $paymentMethods = $this->getPaymentMethodProvider()->getPaymentMethodsForOrder($order); $paymentMethods->map(function (PaymentMethod $paymentMethod) use ($radioGroup) { $radioGroup->addOptionToSelect($paymentMethod->getId(), $paymentMethod->translate()->getName()); }); }
php
private function addPaymentMethods(Order $order, ElementInterface $radioGroup) { $paymentMethods = $this->getPaymentMethodProvider()->getPaymentMethodsForOrder($order); $paymentMethods->map(function (PaymentMethod $paymentMethod) use ($radioGroup) { $radioGroup->addOptionToSelect($paymentMethod->getId(), $paymentMethod->translate()->getName()); }); }
[ "private", "function", "addPaymentMethods", "(", "Order", "$", "order", ",", "ElementInterface", "$", "radioGroup", ")", "{", "$", "paymentMethods", "=", "$", "this", "->", "getPaymentMethodProvider", "(", ")", "->", "getPaymentMethodsForOrder", "(", "$", "order", ")", ";", "$", "paymentMethods", "->", "map", "(", "function", "(", "PaymentMethod", "$", "paymentMethod", ")", "use", "(", "$", "radioGroup", ")", "{", "$", "radioGroup", "->", "addOptionToSelect", "(", "$", "paymentMethod", "->", "getId", "(", ")", ",", "$", "paymentMethod", "->", "translate", "(", ")", "->", "getName", "(", ")", ")", ";", "}", ")", ";", "}" ]
Adds payment method options to select @param Order $order @param ElementInterface|RadioGroup $radioGroup
[ "Adds", "payment", "method", "options", "to", "select" ]
train
https://github.com/WellCommerce/OrderBundle/blob/d72cfb51eab7a1f66f186900d1e2d533a822c424/Form/Front/CartFormBuilder.php#L129-L136
drpdigital/json-api-parser
src/JsonApiParser.php
JsonApiParser.parse
public function parse(array $input) { $this->data = Arr::get($input, 'data'); if ($this->data === null) { return null; } $this->included = Arr::get($input, 'included', []); $this->start(); return $this->resolver->getResolved(); }
php
public function parse(array $input) { $this->data = Arr::get($input, 'data'); if ($this->data === null) { return null; } $this->included = Arr::get($input, 'included', []); $this->start(); return $this->resolver->getResolved(); }
[ "public", "function", "parse", "(", "array", "$", "input", ")", "{", "$", "this", "->", "data", "=", "Arr", "::", "get", "(", "$", "input", ",", "'data'", ")", ";", "if", "(", "$", "this", "->", "data", "===", "null", ")", "{", "return", "null", ";", "}", "$", "this", "->", "included", "=", "Arr", "::", "get", "(", "$", "input", ",", "'included'", ",", "[", "]", ")", ";", "$", "this", "->", "start", "(", ")", ";", "return", "$", "this", "->", "resolver", "->", "getResolved", "(", ")", ";", "}" ]
Parse the data given Returns all the models that were resolved. @param array $input @return \Drp\JsonApiParser\ResolvedCollection|null @throws \ReflectionException @throws \Drp\JsonApiParser\Exceptions\MissingResolverException
[ "Parse", "the", "data", "given" ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/JsonApiParser.php#L47-L59
drpdigital/json-api-parser
src/JsonApiParser.php
JsonApiParser.resolver
public function resolver($resourceNames, $callback) { $resourceNames = Arr::wrap($resourceNames); foreach ($resourceNames as $name) { $this->resolver->bind($name, $callback); } return $this; }
php
public function resolver($resourceNames, $callback) { $resourceNames = Arr::wrap($resourceNames); foreach ($resourceNames as $name) { $this->resolver->bind($name, $callback); } return $this; }
[ "public", "function", "resolver", "(", "$", "resourceNames", ",", "$", "callback", ")", "{", "$", "resourceNames", "=", "Arr", "::", "wrap", "(", "$", "resourceNames", ")", ";", "foreach", "(", "$", "resourceNames", "as", "$", "name", ")", "{", "$", "this", "->", "resolver", "->", "bind", "(", "$", "name", ",", "$", "callback", ")", ";", "}", "return", "$", "this", ";", "}" ]
Adds the callbacks for resolve the different objects in the response @param array|string $resourceNames @param callable|string $callback @return JsonApiParser
[ "Adds", "the", "callbacks", "for", "resolve", "the", "different", "objects", "in", "the", "response" ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/JsonApiParser.php#L68-L77
drpdigital/json-api-parser
src/JsonApiParser.php
JsonApiParser.fetcher
public function fetcher($className, $relationshipName, $callback = null) { $this->resolver->bindFetcher($className, $relationshipName, $callback); return $this; }
php
public function fetcher($className, $relationshipName, $callback = null) { $this->resolver->bindFetcher($className, $relationshipName, $callback); return $this; }
[ "public", "function", "fetcher", "(", "$", "className", ",", "$", "relationshipName", ",", "$", "callback", "=", "null", ")", "{", "$", "this", "->", "resolver", "->", "bindFetcher", "(", "$", "className", ",", "$", "relationshipName", ",", "$", "callback", ")", ";", "return", "$", "this", ";", "}" ]
Add a callback for a class that when called will return an existing instance of a relationship. This callback will be called when trying to resolve a parameter dependency on a resolver callback. The callback will only be given the id of the relationship it needs to be fetched. @param string|array $className @param string|callable $relationshipName This can be an optional relationship name or the callable for the fetcher. @param callable|string $callback @return static
[ "Add", "a", "callback", "for", "a", "class", "that", "when", "called", "will", "return", "an", "existing", "instance", "of", "a", "relationship", "." ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/JsonApiParser.php#L93-L98
drpdigital/json-api-parser
src/JsonApiParser.php
JsonApiParser.start
private function start() { if (Arr::is_assoc($this->data)) { $this->data = [$this->data]; } foreach ($this->data as $data) { $relationshipsToProcess = $this->resolveResource($data); $this->resolveRelationships($relationshipsToProcess); } }
php
private function start() { if (Arr::is_assoc($this->data)) { $this->data = [$this->data]; } foreach ($this->data as $data) { $relationshipsToProcess = $this->resolveResource($data); $this->resolveRelationships($relationshipsToProcess); } }
[ "private", "function", "start", "(", ")", "{", "if", "(", "Arr", "::", "is_assoc", "(", "$", "this", "->", "data", ")", ")", "{", "$", "this", "->", "data", "=", "[", "$", "this", "->", "data", "]", ";", "}", "foreach", "(", "$", "this", "->", "data", "as", "$", "data", ")", "{", "$", "relationshipsToProcess", "=", "$", "this", "->", "resolveResource", "(", "$", "data", ")", ";", "$", "this", "->", "resolveRelationships", "(", "$", "relationshipsToProcess", ")", ";", "}", "}" ]
Starts the parsing and creating of the relationships. @return void @throws \ReflectionException @throws \Drp\JsonApiParser\Exceptions\MissingResolverException
[ "Starts", "the", "parsing", "and", "creating", "of", "the", "relationships", "." ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/JsonApiParser.php#L107-L117
drpdigital/json-api-parser
src/JsonApiParser.php
JsonApiParser.getIncludedResource
private function getIncludedResource($id, $type) { foreach ($this->included as $included) { $includedId = Arr::get($included, 'id'); $includedType = Arr::get($included, 'type'); if ((string) $includedType === (string) $type && (string) $includedId === (string) $id) { return $included; } } return $this->getDefaultIncludedResource($id, $type); }
php
private function getIncludedResource($id, $type) { foreach ($this->included as $included) { $includedId = Arr::get($included, 'id'); $includedType = Arr::get($included, 'type'); if ((string) $includedType === (string) $type && (string) $includedId === (string) $id) { return $included; } } return $this->getDefaultIncludedResource($id, $type); }
[ "private", "function", "getIncludedResource", "(", "$", "id", ",", "$", "type", ")", "{", "foreach", "(", "$", "this", "->", "included", "as", "$", "included", ")", "{", "$", "includedId", "=", "Arr", "::", "get", "(", "$", "included", ",", "'id'", ")", ";", "$", "includedType", "=", "Arr", "::", "get", "(", "$", "included", ",", "'type'", ")", ";", "if", "(", "(", "string", ")", "$", "includedType", "===", "(", "string", ")", "$", "type", "&&", "(", "string", ")", "$", "includedId", "===", "(", "string", ")", "$", "id", ")", "{", "return", "$", "included", ";", "}", "}", "return", "$", "this", "->", "getDefaultIncludedResource", "(", "$", "id", ",", "$", "type", ")", ";", "}" ]
Get a resource that is in the included array Returns default resource if it was not able to find a resource with the given type and id. @param integer $id @param string $type @return bool|mixed
[ "Get", "a", "resource", "that", "is", "in", "the", "included", "array" ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/JsonApiParser.php#L226-L238
drpdigital/json-api-parser
src/JsonApiParser.php
JsonApiParser.resolveRelationships
private function resolveRelationships(array $relationshipsToProcess) { $iterator = new \ArrayIterator($relationshipsToProcess); while ($iterator->valid()) { $resolver = $iterator->current(); if (is_callable($resolver) === false) { $iterator->next(); continue; } $relationships = $resolver(); foreach ($relationships as $relationship) { $iterator->append($relationship); } $iterator->next(); } }
php
private function resolveRelationships(array $relationshipsToProcess) { $iterator = new \ArrayIterator($relationshipsToProcess); while ($iterator->valid()) { $resolver = $iterator->current(); if (is_callable($resolver) === false) { $iterator->next(); continue; } $relationships = $resolver(); foreach ($relationships as $relationship) { $iterator->append($relationship); } $iterator->next(); } }
[ "private", "function", "resolveRelationships", "(", "array", "$", "relationshipsToProcess", ")", "{", "$", "iterator", "=", "new", "\\", "ArrayIterator", "(", "$", "relationshipsToProcess", ")", ";", "while", "(", "$", "iterator", "->", "valid", "(", ")", ")", "{", "$", "resolver", "=", "$", "iterator", "->", "current", "(", ")", ";", "if", "(", "is_callable", "(", "$", "resolver", ")", "===", "false", ")", "{", "$", "iterator", "->", "next", "(", ")", ";", "continue", ";", "}", "$", "relationships", "=", "$", "resolver", "(", ")", ";", "foreach", "(", "$", "relationships", "as", "$", "relationship", ")", "{", "$", "iterator", "->", "append", "(", "$", "relationship", ")", ";", "}", "$", "iterator", "->", "next", "(", ")", ";", "}", "}" ]
Iterate over the relationship resolver (closures) that have been returned. @param array $relationshipsToProcess @return void
[ "Iterate", "over", "the", "relationship", "resolver", "(", "closures", ")", "that", "have", "been", "returned", "." ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/JsonApiParser.php#L261-L278
drpdigital/json-api-parser
src/JsonApiParser.php
JsonApiParser.processResourceData
protected function processResourceData(array $resourceData, array $parentModels, $type) { return $this->resolver->resolve($type, $resourceData, $parentModels); }
php
protected function processResourceData(array $resourceData, array $parentModels, $type) { return $this->resolver->resolve($type, $resourceData, $parentModels); }
[ "protected", "function", "processResourceData", "(", "array", "$", "resourceData", ",", "array", "$", "parentModels", ",", "$", "type", ")", "{", "return", "$", "this", "->", "resolver", "->", "resolve", "(", "$", "type", ",", "$", "resourceData", ",", "$", "parentModels", ")", ";", "}" ]
Create model from data given. @param array $resourceData @param array $parentModels @param string $type @return mixed @throws \ReflectionException @throws \Drp\JsonApiParser\Exceptions\MissingResolverException
[ "Create", "model", "from", "data", "given", "." ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/JsonApiParser.php#L290-L293
dakalab/division-code
src/DivisionCode/DivisionCode.php
DivisionCode.get
public function get($code = null): string { if (!$this->validate($code)) { throw new \InvalidArgumentException('Invalid code'); } return isset(self::$codes[$code]) ? self::$codes[$code] : ''; }
php
public function get($code = null): string { if (!$this->validate($code)) { throw new \InvalidArgumentException('Invalid code'); } return isset(self::$codes[$code]) ? self::$codes[$code] : ''; }
[ "public", "function", "get", "(", "$", "code", "=", "null", ")", ":", "string", "{", "if", "(", "!", "$", "this", "->", "validate", "(", "$", "code", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid code'", ")", ";", "}", "return", "isset", "(", "self", "::", "$", "codes", "[", "$", "code", "]", ")", "?", "self", "::", "$", "codes", "[", "$", "code", "]", ":", "''", ";", "}" ]
Get local name by code @param string|int $code @throws \InvalidArgumentException @return string
[ "Get", "local", "name", "by", "code" ]
train
https://github.com/dakalab/division-code/blob/f8b2c4c7981c49e1bf6f203425b89ae94087d99f/src/DivisionCode/DivisionCode.php#L62-L69
dakalab/division-code
src/DivisionCode/DivisionCode.php
DivisionCode.getCity
public function getCity($code): string { $provinceCode = substr($code, 0, 2) . '0000'; $cityCode = substr($code, 0, 4) . '00'; if ($provinceCode != $cityCode) { return $this->get($cityCode); } return ''; }
php
public function getCity($code): string { $provinceCode = substr($code, 0, 2) . '0000'; $cityCode = substr($code, 0, 4) . '00'; if ($provinceCode != $cityCode) { return $this->get($cityCode); } return ''; }
[ "public", "function", "getCity", "(", "$", "code", ")", ":", "string", "{", "$", "provinceCode", "=", "substr", "(", "$", "code", ",", "0", ",", "2", ")", ".", "'0000'", ";", "$", "cityCode", "=", "substr", "(", "$", "code", ",", "0", ",", "4", ")", ".", "'00'", ";", "if", "(", "$", "provinceCode", "!=", "$", "cityCode", ")", "{", "return", "$", "this", "->", "get", "(", "$", "cityCode", ")", ";", "}", "return", "''", ";", "}" ]
Get the city by code @param string|int $code @return string
[ "Get", "the", "city", "by", "code" ]
train
https://github.com/dakalab/division-code/blob/f8b2c4c7981c49e1bf6f203425b89ae94087d99f/src/DivisionCode/DivisionCode.php#L90-L99
dakalab/division-code
src/DivisionCode/DivisionCode.php
DivisionCode.getAddress
public function getAddress($code): string { return $this->getProvince($code) . $this->getCity($code) . $this->getCounty($code); }
php
public function getAddress($code): string { return $this->getProvince($code) . $this->getCity($code) . $this->getCounty($code); }
[ "public", "function", "getAddress", "(", "$", "code", ")", ":", "string", "{", "return", "$", "this", "->", "getProvince", "(", "$", "code", ")", ".", "$", "this", "->", "getCity", "(", "$", "code", ")", ".", "$", "this", "->", "getCounty", "(", "$", "code", ")", ";", "}" ]
Get the address by code @param string|int $code @return string
[ "Get", "the", "address", "by", "code" ]
train
https://github.com/dakalab/division-code/blob/f8b2c4c7981c49e1bf6f203425b89ae94087d99f/src/DivisionCode/DivisionCode.php#L122-L125
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/FilesEngine.php
FilesEngine.search
public function search($query, $page = 1) { return $this->get(sprintf( 'files/search/%s/page/%d', rawurlencode(trim($query)), $page )); }
php
public function search($query, $page = 1) { return $this->get(sprintf( 'files/search/%s/page/%d', rawurlencode(trim($query)), $page )); }
[ "public", "function", "search", "(", "$", "query", ",", "$", "page", "=", "1", ")", "{", "return", "$", "this", "->", "get", "(", "sprintf", "(", "'files/search/%s/page/%d'", ",", "rawurlencode", "(", "trim", "(", "$", "query", ")", ")", ",", "$", "page", ")", ")", ";", "}" ]
Returns an array of files matching the given search query. @param string $query Search query @param integer $page Page number @return array
[ "Returns", "an", "array", "of", "files", "matching", "the", "given", "search", "query", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/FilesEngine.php#L46-L53
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/FilesEngine.php
FilesEngine.upload
public function upload($file, $parentID = 0) { if (!$file = realpath($file)) { throw new \Exception('File not found'); } return $this->uploadFile('files/upload', [ 'parent_id' => $parentID, 'file' => "@{$file}" ]); }
php
public function upload($file, $parentID = 0) { if (!$file = realpath($file)) { throw new \Exception('File not found'); } return $this->uploadFile('files/upload', [ 'parent_id' => $parentID, 'file' => "@{$file}" ]); }
[ "public", "function", "upload", "(", "$", "file", ",", "$", "parentID", "=", "0", ")", "{", "if", "(", "!", "$", "file", "=", "realpath", "(", "$", "file", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'File not found'", ")", ";", "}", "return", "$", "this", "->", "uploadFile", "(", "'files/upload'", ",", "[", "'parent_id'", "=>", "$", "parentID", ",", "'file'", "=>", "\"@{$file}\"", "]", ")", ";", "}" ]
Uploads a local file to your account. NOTE 1: The response differs based on the uploaded file. For regular files, the array key containing the info is 'file', but for torrents it's 'transfer'. @see https://api.put.io/v2/docs/#files-upload NOTE 2: Files need to be read into the memory when using NATIVE functions. Keep that in mind when uploading large files or running multiple instances. @param string $file Path to local file. @param integer $parentID ID of upload folder. @return mixed @throws \Exception
[ "Uploads", "a", "local", "file", "to", "your", "account", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/FilesEngine.php#L73-L83
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/FilesEngine.php
FilesEngine.makeDir
public function makeDir($name, $parentID = 0) { $data = [ 'name' => $name, 'parent_id' => $parentID ]; return $this->post('files/create-folder', $data, \false, 'file'); }
php
public function makeDir($name, $parentID = 0) { $data = [ 'name' => $name, 'parent_id' => $parentID ]; return $this->post('files/create-folder', $data, \false, 'file'); }
[ "public", "function", "makeDir", "(", "$", "name", ",", "$", "parentID", "=", "0", ")", "{", "$", "data", "=", "[", "'name'", "=>", "$", "name", ",", "'parent_id'", "=>", "$", "parentID", "]", ";", "return", "$", "this", "->", "post", "(", "'files/create-folder'", ",", "$", "data", ",", "\\", "false", ",", "'file'", ")", ";", "}" ]
Creates a new folder. Returns folder info on success, false on error. @param string $name Name of the new folder. @param integer $parentID ID of the parent folder. @return mixed
[ "Creates", "a", "new", "folder", ".", "Returns", "folder", "info", "on", "success", "false", "on", "error", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/FilesEngine.php#L92-L100
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/FilesEngine.php
FilesEngine.delete
public function delete($fileIDs) { if (is_array($fileIDs)) { $fileIDs = implode(',', $fileIDs); } $data = [ 'file_ids' => $fileIDs ]; return $this->post('files/delete', $data, \true); }
php
public function delete($fileIDs) { if (is_array($fileIDs)) { $fileIDs = implode(',', $fileIDs); } $data = [ 'file_ids' => $fileIDs ]; return $this->post('files/delete', $data, \true); }
[ "public", "function", "delete", "(", "$", "fileIDs", ")", "{", "if", "(", "is_array", "(", "$", "fileIDs", ")", ")", "{", "$", "fileIDs", "=", "implode", "(", "','", ",", "$", "fileIDs", ")", ";", "}", "$", "data", "=", "[", "'file_ids'", "=>", "$", "fileIDs", "]", ";", "return", "$", "this", "->", "post", "(", "'files/delete'", ",", "$", "data", ",", "\\", "true", ")", ";", "}" ]
Deletes files from your account. @param mixed $fileIDs IDs of files you want to delete. Array or integer. @return boolean
[ "Deletes", "files", "from", "your", "account", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/FilesEngine.php#L119-L130
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/FilesEngine.php
FilesEngine.rename
public function rename($fileID, $name) { $data = [ 'file_id' => $fileID, 'name' => $name ]; return $this->post('files/rename', $data, \true); }
php
public function rename($fileID, $name) { $data = [ 'file_id' => $fileID, 'name' => $name ]; return $this->post('files/rename', $data, \true); }
[ "public", "function", "rename", "(", "$", "fileID", ",", "$", "name", ")", "{", "$", "data", "=", "[", "'file_id'", "=>", "$", "fileID", ",", "'name'", "=>", "$", "name", "]", ";", "return", "$", "this", "->", "post", "(", "'files/rename'", ",", "$", "data", ",", "\\", "true", ")", ";", "}" ]
Renames a file. @param integer $fileID ID of the file you want to rename. @param string $name New name of the file. @return boolean
[ "Renames", "a", "file", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/FilesEngine.php#L139-L147
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/FilesEngine.php
FilesEngine.move
public function move($fileIDs, $parentID) { if (is_array($fileIDs)) { $fileIDs = implode(',', $fileIDs); } $data = [ 'file_ids' => $fileIDs, 'parent_id' => $parentID ]; return $this->post('files/move', $data, \true); }
php
public function move($fileIDs, $parentID) { if (is_array($fileIDs)) { $fileIDs = implode(',', $fileIDs); } $data = [ 'file_ids' => $fileIDs, 'parent_id' => $parentID ]; return $this->post('files/move', $data, \true); }
[ "public", "function", "move", "(", "$", "fileIDs", ",", "$", "parentID", ")", "{", "if", "(", "is_array", "(", "$", "fileIDs", ")", ")", "{", "$", "fileIDs", "=", "implode", "(", "','", ",", "$", "fileIDs", ")", ";", "}", "$", "data", "=", "[", "'file_ids'", "=>", "$", "fileIDs", ",", "'parent_id'", "=>", "$", "parentID", "]", ";", "return", "$", "this", "->", "post", "(", "'files/move'", ",", "$", "data", ",", "\\", "true", ")", ";", "}" ]
Moves one of more files to a new directory. @param mixed $fileIDs IDs of files you want to move. Array or integer. @param integer $parentID ID of the folder you want to move the files to. @return boolean
[ "Moves", "one", "of", "more", "files", "to", "a", "new", "directory", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/FilesEngine.php#L156-L168
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/FilesEngine.php
FilesEngine.download
public function download($fileID, $saveAs = '', $isMP4 = \false) { if ($saveAs === '') { if (!$info = $this->info($fileID)) { return \false; } $saveAs = $info['name']; } $mp4 = $isMP4 ? 'mp4/' : ''; return $this->downloadFile("files/{$fileID}/{$mp4}download", $saveAs); }
php
public function download($fileID, $saveAs = '', $isMP4 = \false) { if ($saveAs === '') { if (!$info = $this->info($fileID)) { return \false; } $saveAs = $info['name']; } $mp4 = $isMP4 ? 'mp4/' : ''; return $this->downloadFile("files/{$fileID}/{$mp4}download", $saveAs); }
[ "public", "function", "download", "(", "$", "fileID", ",", "$", "saveAs", "=", "''", ",", "$", "isMP4", "=", "\\", "false", ")", "{", "if", "(", "$", "saveAs", "===", "''", ")", "{", "if", "(", "!", "$", "info", "=", "$", "this", "->", "info", "(", "$", "fileID", ")", ")", "{", "return", "\\", "false", ";", "}", "$", "saveAs", "=", "$", "info", "[", "'name'", "]", ";", "}", "$", "mp4", "=", "$", "isMP4", "?", "'mp4/'", ":", "''", ";", "return", "$", "this", "->", "downloadFile", "(", "\"files/{$fileID}/{$mp4}download\"", ",", "$", "saveAs", ")", ";", "}" ]
Downloads a remote file to the local server. Second parameter '$saveAs' is optional, but very recommended. If it's left empty, it'll query for the original file name by sending an additional HTTP request. @param integer $fileID ID of the file you want to download. @param string $saveAs Local path you want to save the file to. @param boolean $isMP4 Tells whether or not to download the MP4 version of a file. @return boolean
[ "Downloads", "a", "remote", "file", "to", "the", "local", "server", ".", "Second", "parameter", "$saveAs", "is", "optional", "but", "very", "recommended", ".", "If", "it", "s", "left", "empty", "it", "ll", "query", "for", "the", "original", "file", "name", "by", "sending", "an", "additional", "HTTP", "request", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/FilesEngine.php#L203-L215
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/FilesEngine.php
FilesEngine.getDownloadURL
public function getDownloadURL($fileID, $isMP4 = \false) { return sprintf( 'https://api.put.io/v2/files/%d/%sdownload?oauth_token=%s', $fileID, $isMP4 ? 'mp4/' : '', $this->putio->getOAuthToken() ); }
php
public function getDownloadURL($fileID, $isMP4 = \false) { return sprintf( 'https://api.put.io/v2/files/%d/%sdownload?oauth_token=%s', $fileID, $isMP4 ? 'mp4/' : '', $this->putio->getOAuthToken() ); }
[ "public", "function", "getDownloadURL", "(", "$", "fileID", ",", "$", "isMP4", "=", "\\", "false", ")", "{", "return", "sprintf", "(", "'https://api.put.io/v2/files/%d/%sdownload?oauth_token=%s'", ",", "$", "fileID", ",", "$", "isMP4", "?", "'mp4/'", ":", "''", ",", "$", "this", "->", "putio", "->", "getOAuthToken", "(", ")", ")", ";", "}" ]
Returns the download URL of a given file ID. ATTENTION: The URL includes your OAuth Token! Don't share this URL with strangers. @param integer $fileID ID of the file you want to download. @param boolean $isMP4 Tells whether or not to download the MP4 version of a file. @return string
[ "Returns", "the", "download", "URL", "of", "a", "given", "file", "ID", ".", "ATTENTION", ":", "The", "URL", "includes", "your", "OAuth", "Token!", "Don", "t", "share", "this", "URL", "with", "strangers", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/FilesEngine.php#L242-L250
thecodingmachine/utils.graphics.mouf-imagine
src/Mouf/Utils/Graphics/MoufImagine/Controller/ImagePresetController.php
ImagePresetController.deletePreset
private function deletePreset ($imagePath) { $finalPath = ROOT_PATH . $this->url . DIRECTORY_SEPARATOR . $imagePath; if (file_exists($finalPath)){ unlink($finalPath); } }
php
private function deletePreset ($imagePath) { $finalPath = ROOT_PATH . $this->url . DIRECTORY_SEPARATOR . $imagePath; if (file_exists($finalPath)){ unlink($finalPath); } }
[ "private", "function", "deletePreset", "(", "$", "imagePath", ")", "{", "$", "finalPath", "=", "ROOT_PATH", ".", "$", "this", "->", "url", ".", "DIRECTORY_SEPARATOR", ".", "$", "imagePath", ";", "if", "(", "file_exists", "(", "$", "finalPath", ")", ")", "{", "unlink", "(", "$", "finalPath", ")", ";", "}", "}" ]
Delete a preset of an image @param $imagePath
[ "Delete", "a", "preset", "of", "an", "image" ]
train
https://github.com/thecodingmachine/utils.graphics.mouf-imagine/blob/54366dec4839569290bf79a4ffd41b032461779b/src/Mouf/Utils/Graphics/MoufImagine/Controller/ImagePresetController.php#L174-L179
thecodingmachine/utils.graphics.mouf-imagine
src/Mouf/Utils/Graphics/MoufImagine/Controller/ImagePresetController.php
ImagePresetController.createPresets
public static function createPresets($path = null, $callback = null) { $moufManager = MoufManager::getMoufManager(); $instances = $moufManager->findInstances('Mouf\\Utils\\Graphics\\MoufImagine\\Controller\\ImagePresetController'); foreach ($instances as $instanceName) { $instance = $moufManager->getInstance($instanceName); if ($path && strpos($path, $instance->originalPath) !== false && $instance->createPresetsEnabled === true) { $imagePath = substr($path, strlen($instance->originalPath) + 1); $instance->image($imagePath); if(is_callable($callback)) { $finalPath = ROOT_PATH . $instance->url . DIRECTORY_SEPARATOR . $imagePath; $callback($finalPath); } } } }
php
public static function createPresets($path = null, $callback = null) { $moufManager = MoufManager::getMoufManager(); $instances = $moufManager->findInstances('Mouf\\Utils\\Graphics\\MoufImagine\\Controller\\ImagePresetController'); foreach ($instances as $instanceName) { $instance = $moufManager->getInstance($instanceName); if ($path && strpos($path, $instance->originalPath) !== false && $instance->createPresetsEnabled === true) { $imagePath = substr($path, strlen($instance->originalPath) + 1); $instance->image($imagePath); if(is_callable($callback)) { $finalPath = ROOT_PATH . $instance->url . DIRECTORY_SEPARATOR . $imagePath; $callback($finalPath); } } } }
[ "public", "static", "function", "createPresets", "(", "$", "path", "=", "null", ",", "$", "callback", "=", "null", ")", "{", "$", "moufManager", "=", "MoufManager", "::", "getMoufManager", "(", ")", ";", "$", "instances", "=", "$", "moufManager", "->", "findInstances", "(", "'Mouf\\\\Utils\\\\Graphics\\\\MoufImagine\\\\Controller\\\\ImagePresetController'", ")", ";", "foreach", "(", "$", "instances", "as", "$", "instanceName", ")", "{", "$", "instance", "=", "$", "moufManager", "->", "getInstance", "(", "$", "instanceName", ")", ";", "if", "(", "$", "path", "&&", "strpos", "(", "$", "path", ",", "$", "instance", "->", "originalPath", ")", "!==", "false", "&&", "$", "instance", "->", "createPresetsEnabled", "===", "true", ")", "{", "$", "imagePath", "=", "substr", "(", "$", "path", ",", "strlen", "(", "$", "instance", "->", "originalPath", ")", "+", "1", ")", ";", "$", "instance", "->", "image", "(", "$", "imagePath", ")", ";", "if", "(", "is_callable", "(", "$", "callback", ")", ")", "{", "$", "finalPath", "=", "ROOT_PATH", ".", "$", "instance", "->", "url", ".", "DIRECTORY_SEPARATOR", ".", "$", "imagePath", ";", "$", "callback", "(", "$", "finalPath", ")", ";", "}", "}", "}", "}" ]
Create presets of an image @param string $path
[ "Create", "presets", "of", "an", "image" ]
train
https://github.com/thecodingmachine/utils.graphics.mouf-imagine/blob/54366dec4839569290bf79a4ffd41b032461779b/src/Mouf/Utils/Graphics/MoufImagine/Controller/ImagePresetController.php#L185-L200
thecodingmachine/utils.graphics.mouf-imagine
src/Mouf/Utils/Graphics/MoufImagine/Controller/ImagePresetController.php
ImagePresetController.purgePresets
public static function purgePresets($path = null, $callback = null) { $moufManager = MoufManager::getMoufManager(); $instances = $moufManager->findInstances('Mouf\\Utils\\Graphics\\MoufImagine\\Controller\\ImagePresetController'); foreach ($instances as $instanceName) { $instance = $moufManager->getInstance($instanceName); if ($path && strpos($path, $instance->originalPath) !== false) { $imagePath = substr($path, strlen($instance->originalPath) + 1); $instance->deletePreset($imagePath); if(is_callable($callback)) { $finalPath = ROOT_PATH . $instance->url . DIRECTORY_SEPARATOR . $imagePath; $callback($finalPath); } } } }
php
public static function purgePresets($path = null, $callback = null) { $moufManager = MoufManager::getMoufManager(); $instances = $moufManager->findInstances('Mouf\\Utils\\Graphics\\MoufImagine\\Controller\\ImagePresetController'); foreach ($instances as $instanceName) { $instance = $moufManager->getInstance($instanceName); if ($path && strpos($path, $instance->originalPath) !== false) { $imagePath = substr($path, strlen($instance->originalPath) + 1); $instance->deletePreset($imagePath); if(is_callable($callback)) { $finalPath = ROOT_PATH . $instance->url . DIRECTORY_SEPARATOR . $imagePath; $callback($finalPath); } } } }
[ "public", "static", "function", "purgePresets", "(", "$", "path", "=", "null", ",", "$", "callback", "=", "null", ")", "{", "$", "moufManager", "=", "MoufManager", "::", "getMoufManager", "(", ")", ";", "$", "instances", "=", "$", "moufManager", "->", "findInstances", "(", "'Mouf\\\\Utils\\\\Graphics\\\\MoufImagine\\\\Controller\\\\ImagePresetController'", ")", ";", "foreach", "(", "$", "instances", "as", "$", "instanceName", ")", "{", "$", "instance", "=", "$", "moufManager", "->", "getInstance", "(", "$", "instanceName", ")", ";", "if", "(", "$", "path", "&&", "strpos", "(", "$", "path", ",", "$", "instance", "->", "originalPath", ")", "!==", "false", ")", "{", "$", "imagePath", "=", "substr", "(", "$", "path", ",", "strlen", "(", "$", "instance", "->", "originalPath", ")", "+", "1", ")", ";", "$", "instance", "->", "deletePreset", "(", "$", "imagePath", ")", ";", "if", "(", "is_callable", "(", "$", "callback", ")", ")", "{", "$", "finalPath", "=", "ROOT_PATH", ".", "$", "instance", "->", "url", ".", "DIRECTORY_SEPARATOR", ".", "$", "imagePath", ";", "$", "callback", "(", "$", "finalPath", ")", ";", "}", "}", "}", "}" ]
Purge presets of an image @param string $path
[ "Purge", "presets", "of", "an", "image" ]
train
https://github.com/thecodingmachine/utils.graphics.mouf-imagine/blob/54366dec4839569290bf79a4ffd41b032461779b/src/Mouf/Utils/Graphics/MoufImagine/Controller/ImagePresetController.php#L206-L221
thecodingmachine/utils.graphics.mouf-imagine
src/Mouf/Utils/Graphics/MoufImagine/Controller/ImagePresetController.php
ImagePresetController.getMimeType
private function getMimeType($format) { $format = $this->normalizeFormat($format); static $mimeTypes = array( 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'wbmp' => 'image/vnd.wap.wbmp', 'xbm' => 'image/xbm', ); if (!isset($mimeTypes[$format])) { throw new \RuntimeException('Invalid format'); } return $mimeTypes[$format]; }
php
private function getMimeType($format) { $format = $this->normalizeFormat($format); static $mimeTypes = array( 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'wbmp' => 'image/vnd.wap.wbmp', 'xbm' => 'image/xbm', ); if (!isset($mimeTypes[$format])) { throw new \RuntimeException('Invalid format'); } return $mimeTypes[$format]; }
[ "private", "function", "getMimeType", "(", "$", "format", ")", "{", "$", "format", "=", "$", "this", "->", "normalizeFormat", "(", "$", "format", ")", ";", "static", "$", "mimeTypes", "=", "array", "(", "'jpeg'", "=>", "'image/jpeg'", ",", "'gif'", "=>", "'image/gif'", ",", "'png'", "=>", "'image/png'", ",", "'wbmp'", "=>", "'image/vnd.wap.wbmp'", ",", "'xbm'", "=>", "'image/xbm'", ",", ")", ";", "if", "(", "!", "isset", "(", "$", "mimeTypes", "[", "$", "format", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Invalid format'", ")", ";", "}", "return", "$", "mimeTypes", "[", "$", "format", "]", ";", "}" ]
Internal Get the mime type based on format. @param string $format @return string mime-type @throws \RuntimeException
[ "Internal" ]
train
https://github.com/thecodingmachine/utils.graphics.mouf-imagine/blob/54366dec4839569290bf79a4ffd41b032461779b/src/Mouf/Utils/Graphics/MoufImagine/Controller/ImagePresetController.php#L311-L328
polidog/esa-php
src/Exception/ClientException.php
ClientException.newException
public static function newException(\Exception $e, $method, $path, array $params) { $self = new self(sprintf('Api method error: %s : %s', $method, $path), $e->getCode(), $e); $self->method = $method; $self->path = $path; $self->params = $params; return $self; }
php
public static function newException(\Exception $e, $method, $path, array $params) { $self = new self(sprintf('Api method error: %s : %s', $method, $path), $e->getCode(), $e); $self->method = $method; $self->path = $path; $self->params = $params; return $self; }
[ "public", "static", "function", "newException", "(", "\\", "Exception", "$", "e", ",", "$", "method", ",", "$", "path", ",", "array", "$", "params", ")", "{", "$", "self", "=", "new", "self", "(", "sprintf", "(", "'Api method error: %s : %s'", ",", "$", "method", ",", "$", "path", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "$", "self", "->", "method", "=", "$", "method", ";", "$", "self", "->", "path", "=", "$", "path", ";", "$", "self", "->", "params", "=", "$", "params", ";", "return", "$", "self", ";", "}" ]
@param \Exception $e @param $method @param $path @param array $params @return ClientException
[ "@param", "\\", "Exception", "$e", "@param", "$method", "@param", "$path", "@param", "array", "$params" ]
train
https://github.com/polidog/esa-php/blob/c5badbd027d73eebcd3cd388487b7c793323bb14/src/Exception/ClientException.php#L54-L62
raoul2000/yii2-twbsmaxlength-widget
TwbsMaxlength.php
TwbsMaxlength.initClientOptions
protected function initClientOptions() { if(! isset($this->options['maxlength']) ){ if( $this->hasModel()) { $this->options['maxlength'] = self::getMaxLength($this->model, Html::getAttributeName($this->attribute)); } } if( !isset($this->clientOptions['threshold']) && $this->options['maxlength'] != null) { $this->initThreshold(); } }
php
protected function initClientOptions() { if(! isset($this->options['maxlength']) ){ if( $this->hasModel()) { $this->options['maxlength'] = self::getMaxLength($this->model, Html::getAttributeName($this->attribute)); } } if( !isset($this->clientOptions['threshold']) && $this->options['maxlength'] != null) { $this->initThreshold(); } }
[ "protected", "function", "initClientOptions", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "options", "[", "'maxlength'", "]", ")", ")", "{", "if", "(", "$", "this", "->", "hasModel", "(", ")", ")", "{", "$", "this", "->", "options", "[", "'maxlength'", "]", "=", "self", "::", "getMaxLength", "(", "$", "this", "->", "model", ",", "Html", "::", "getAttributeName", "(", "$", "this", "->", "attribute", ")", ")", ";", "}", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "clientOptions", "[", "'threshold'", "]", ")", "&&", "$", "this", "->", "options", "[", "'maxlength'", "]", "!=", "null", ")", "{", "$", "this", "->", "initThreshold", "(", ")", ";", "}", "}" ]
Initializes client options
[ "Initializes", "client", "options" ]
train
https://github.com/raoul2000/yii2-twbsmaxlength-widget/blob/87ba6bf179a8db398bff0aaee6701a1e6dfc8b3b/TwbsMaxlength.php#L93-L104
raoul2000/yii2-twbsmaxlength-widget
TwbsMaxlength.php
TwbsMaxlength.initThreshold
protected function initThreshold() { switch ($this->thresholdPolicy) { case self::THRESHOLD_TWO_THIRD : $this->clientOptions['threshold'] = ceil($this->options['maxlength'] / 3); break; case self::THRESHOLD_THREE_QUARTERS : $this->clientOptions['threshold'] = ceil($this->options['maxlength'] / 4); break; default: $this->clientOptions['threshold'] = ceil($this->options['maxlength'] / 2); break; } }
php
protected function initThreshold() { switch ($this->thresholdPolicy) { case self::THRESHOLD_TWO_THIRD : $this->clientOptions['threshold'] = ceil($this->options['maxlength'] / 3); break; case self::THRESHOLD_THREE_QUARTERS : $this->clientOptions['threshold'] = ceil($this->options['maxlength'] / 4); break; default: $this->clientOptions['threshold'] = ceil($this->options['maxlength'] / 2); break; } }
[ "protected", "function", "initThreshold", "(", ")", "{", "switch", "(", "$", "this", "->", "thresholdPolicy", ")", "{", "case", "self", "::", "THRESHOLD_TWO_THIRD", ":", "$", "this", "->", "clientOptions", "[", "'threshold'", "]", "=", "ceil", "(", "$", "this", "->", "options", "[", "'maxlength'", "]", "/", "3", ")", ";", "break", ";", "case", "self", "::", "THRESHOLD_THREE_QUARTERS", ":", "$", "this", "->", "clientOptions", "[", "'threshold'", "]", "=", "ceil", "(", "$", "this", "->", "options", "[", "'maxlength'", "]", "/", "4", ")", ";", "break", ";", "default", ":", "$", "this", "->", "clientOptions", "[", "'threshold'", "]", "=", "ceil", "(", "$", "this", "->", "options", "[", "'maxlength'", "]", "/", "2", ")", ";", "break", ";", "}", "}" ]
Initialize the threshold value for the maxlength plugin. Depending on the *thresholdPolicy* option, the *maxlength* value will be divided to get the actual value of the threshold that is used to initialize the plugin.
[ "Initialize", "the", "threshold", "value", "for", "the", "maxlength", "plugin", ".", "Depending", "on", "the", "*", "thresholdPolicy", "*", "option", "the", "*", "maxlength", "*", "value", "will", "be", "divided", "to", "get", "the", "actual", "value", "of", "the", "threshold", "that", "is", "used", "to", "initialize", "the", "plugin", "." ]
train
https://github.com/raoul2000/yii2-twbsmaxlength-widget/blob/87ba6bf179a8db398bff0aaee6701a1e6dfc8b3b/TwbsMaxlength.php#L111-L124