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
eveseat/eseye
src/Cache/MemcachedCache.php
MemcachedCache.buildCacheKey
public function buildCacheKey(string $uri, string $query = ''): string { if ($query != '') $query = $this->hashString($query); return $this->prefix . $this->hashString($uri . $query); }
php
public function buildCacheKey(string $uri, string $query = ''): string { if ($query != '') $query = $this->hashString($query); return $this->prefix . $this->hashString($uri . $query); }
[ "public", "function", "buildCacheKey", "(", "string", "$", "uri", ",", "string", "$", "query", "=", "''", ")", ":", "string", "{", "if", "(", "$", "query", "!=", "''", ")", "$", "query", "=", "$", "this", "->", "hashString", "(", "$", "query", ")",...
@param string $uri @param string $query @return string
[ "@param", "string", "$uri", "@param", "string", "$query" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Cache/MemcachedCache.php#L112-L119
eveseat/eseye
src/Cache/MemcachedCache.php
MemcachedCache.get
public function get(string $uri, string $query = '') { $value = $this->memcached->get($this->buildCacheKey($uri, $query)); if ($value === false) return false; $data = unserialize($value); // If the cached entry is expired and does not have any ETag, remove it. if ($data->expired() && ! $data->hasHeader('ETag')) { $this->forget($uri, $query); return false; } return $data; }
php
public function get(string $uri, string $query = '') { $value = $this->memcached->get($this->buildCacheKey($uri, $query)); if ($value === false) return false; $data = unserialize($value); // If the cached entry is expired and does not have any ETag, remove it. if ($data->expired() && ! $data->hasHeader('ETag')) { $this->forget($uri, $query); return false; } return $data; }
[ "public", "function", "get", "(", "string", "$", "uri", ",", "string", "$", "query", "=", "''", ")", "{", "$", "value", "=", "$", "this", "->", "memcached", "->", "get", "(", "$", "this", "->", "buildCacheKey", "(", "$", "uri", ",", "$", "query", ...
@param string $uri @param string $query @return mixed
[ "@param", "string", "$uri", "@param", "string", "$query" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Cache/MemcachedCache.php#L127-L144
eveseat/eseye
src/Cache/MemcachedCache.php
MemcachedCache.forget
public function forget(string $uri, string $query = '') { return $this->memcached->delete($this->buildCacheKey($uri, $query)); }
php
public function forget(string $uri, string $query = '') { return $this->memcached->delete($this->buildCacheKey($uri, $query)); }
[ "public", "function", "forget", "(", "string", "$", "uri", ",", "string", "$", "query", "=", "''", ")", "{", "return", "$", "this", "->", "memcached", "->", "delete", "(", "$", "this", "->", "buildCacheKey", "(", "$", "uri", ",", "$", "query", ")", ...
@param string $uri @param string $query @return mixed
[ "@param", "string", "$uri", "@param", "string", "$query" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Cache/MemcachedCache.php#L152-L156
eveseat/eseye
src/Cache/MemcachedCache.php
MemcachedCache.has
public function has(string $uri, string $query = ''): bool { return $this->memcached->get($this->buildCacheKey($uri, $query)) !== false; }
php
public function has(string $uri, string $query = ''): bool { return $this->memcached->get($this->buildCacheKey($uri, $query)) !== false; }
[ "public", "function", "has", "(", "string", "$", "uri", ",", "string", "$", "query", "=", "''", ")", ":", "bool", "{", "return", "$", "this", "->", "memcached", "->", "get", "(", "$", "this", "->", "buildCacheKey", "(", "$", "uri", ",", "$", "query...
@param string $uri @param string $query @return bool|mixed
[ "@param", "string", "$uri", "@param", "string", "$query" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Cache/MemcachedCache.php#L164-L168
eveseat/eseye
src/Eseye.php
Eseye.setAuthentication
public function setAuthentication(EsiAuthentication $authentication): self { if (! $authentication->valid()) throw new InvalidContainerDataException('Authentication data invalid/empty'); $this->authentication = $authentication; return $this; }
php
public function setAuthentication(EsiAuthentication $authentication): self { if (! $authentication->valid()) throw new InvalidContainerDataException('Authentication data invalid/empty'); $this->authentication = $authentication; return $this; }
[ "public", "function", "setAuthentication", "(", "EsiAuthentication", "$", "authentication", ")", ":", "self", "{", "if", "(", "!", "$", "authentication", "->", "valid", "(", ")", ")", "throw", "new", "InvalidContainerDataException", "(", "'Authentication data invali...
@param \Seat\Eseye\Containers\EsiAuthentication $authentication @return \Seat\Eseye\Eseye @throws \Seat\Eseye\Exceptions\InvalidContainerDataException
[ "@param", "\\", "Seat", "\\", "Eseye", "\\", "Containers", "\\", "EsiAuthentication", "$authentication" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Eseye.php#L156-L165
eveseat/eseye
src/Eseye.php
Eseye.setRefreshToken
public function setRefreshToken(String $refreshToken): self { $this->authentication = $this->authentication->setRefreshToken($refreshToken); return $this; }
php
public function setRefreshToken(String $refreshToken): self { $this->authentication = $this->authentication->setRefreshToken($refreshToken); return $this; }
[ "public", "function", "setRefreshToken", "(", "String", "$", "refreshToken", ")", ":", "self", "{", "$", "this", "->", "authentication", "=", "$", "this", "->", "authentication", "->", "setRefreshToken", "(", "$", "refreshToken", ")", ";", "return", "$", "th...
@param string $refreshToken @return \Seat\Eseye\Eseye
[ "@param", "string", "$refreshToken" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Eseye.php#L172-L178
eveseat/eseye
src/Eseye.php
Eseye.invoke
public function invoke(string $method, string $uri, array $uri_data = []): EsiResponse { // Check the Access Requirement if (! $this->getAccessChecker()->can( $method, $uri, $this->getFetcher()->getAuthenticationScopes()) ) { // Build the uri so that there is context around what is denied. $uri = $this->buildDataUri($uri, $uri_data); // Log the deny. $this->logger->warning('Access denied to ' . $uri . ' due to ' . 'missing scopes.'); throw new EsiScopeAccessDeniedException('Access denied to ' . $uri); } // Build the URI from the parts we have. $uri = $this->buildDataUri($uri, $uri_data); // Check if there is a cached response we can return if (in_array(strtolower($method), $this->cachable_verb) && $cached = $this->getCache()->get($uri->getPath(), $uri->getQuery()) ) { // Mark the response as one that was loaded from the cache in case no ETag exists if (! $cached->hasHeader('ETag')) $cached->setIsCachedLoad(); // Handling ETag marked response specifically (ignoring the expired time) // Sending a request with the stored ETag in header - if we have a 304 response, data has not been altered. if ($cached->hasHeader('ETag') && $cached->expired()) { $result = $this->rawFetch($method, $uri, $this->getBody(), ['If-None-Match' => $cached->getHeader('ETag')]); if ($result->getErrorCode() == 304) $cached->setIsCachedLoad(); } // In case the result is effectively retrieved from cache, // return the cached element. if ($cached->isCachedLoad()) { // Perform some debug logging $logging_msg = 'Loaded cached response for ' . $method . ' -> ' . $uri; if ($cached->hasHeader('ETag')) $logging_msg = sprintf('%s [%s]', $logging_msg, $cached->getHeader('ETag')); $this->getLogger()->debug($logging_msg); return $cached; } } // Call ESI itself and get the EsiResponse in case it has not already been handled with cache control if (! isset($result)) $result = $this->rawFetch($method, $uri, $this->getBody()); // Cache the response if it was a get and is not already expired if (in_array(strtolower($method), $this->cachable_verb) && ! $result->expired()) $this->getCache()->set($uri->getPath(), $uri->getQuery(), $result); // In preparation for the next request, perform some // self cleanups of this objects request data such as // query string parameters and post bodies. $this->cleanupRequestData(); return $result; }
php
public function invoke(string $method, string $uri, array $uri_data = []): EsiResponse { // Check the Access Requirement if (! $this->getAccessChecker()->can( $method, $uri, $this->getFetcher()->getAuthenticationScopes()) ) { // Build the uri so that there is context around what is denied. $uri = $this->buildDataUri($uri, $uri_data); // Log the deny. $this->logger->warning('Access denied to ' . $uri . ' due to ' . 'missing scopes.'); throw new EsiScopeAccessDeniedException('Access denied to ' . $uri); } // Build the URI from the parts we have. $uri = $this->buildDataUri($uri, $uri_data); // Check if there is a cached response we can return if (in_array(strtolower($method), $this->cachable_verb) && $cached = $this->getCache()->get($uri->getPath(), $uri->getQuery()) ) { // Mark the response as one that was loaded from the cache in case no ETag exists if (! $cached->hasHeader('ETag')) $cached->setIsCachedLoad(); // Handling ETag marked response specifically (ignoring the expired time) // Sending a request with the stored ETag in header - if we have a 304 response, data has not been altered. if ($cached->hasHeader('ETag') && $cached->expired()) { $result = $this->rawFetch($method, $uri, $this->getBody(), ['If-None-Match' => $cached->getHeader('ETag')]); if ($result->getErrorCode() == 304) $cached->setIsCachedLoad(); } // In case the result is effectively retrieved from cache, // return the cached element. if ($cached->isCachedLoad()) { // Perform some debug logging $logging_msg = 'Loaded cached response for ' . $method . ' -> ' . $uri; if ($cached->hasHeader('ETag')) $logging_msg = sprintf('%s [%s]', $logging_msg, $cached->getHeader('ETag')); $this->getLogger()->debug($logging_msg); return $cached; } } // Call ESI itself and get the EsiResponse in case it has not already been handled with cache control if (! isset($result)) $result = $this->rawFetch($method, $uri, $this->getBody()); // Cache the response if it was a get and is not already expired if (in_array(strtolower($method), $this->cachable_verb) && ! $result->expired()) $this->getCache()->set($uri->getPath(), $uri->getQuery(), $result); // In preparation for the next request, perform some // self cleanups of this objects request data such as // query string parameters and post bodies. $this->cleanupRequestData(); return $result; }
[ "public", "function", "invoke", "(", "string", "$", "method", ",", "string", "$", "uri", ",", "array", "$", "uri_data", "=", "[", "]", ")", ":", "EsiResponse", "{", "// Check the Access Requirement", "if", "(", "!", "$", "this", "->", "getAccessChecker", "...
@param string $method @param string $uri @param array $uri_data @return \Seat\Eseye\Containers\EsiResponse @throws \Seat\Eseye\Exceptions\EsiScopeAccessDeniedException @throws \Seat\Eseye\Exceptions\RequestFailedException @throws \Seat\Eseye\Exceptions\InvalidAuthenticationException @throws \Seat\Eseye\Exceptions\InvalidContainerDataException @throws \Seat\Eseye\Exceptions\UriDataMissingException
[ "@param", "string", "$method", "@param", "string", "$uri", "@param", "array", "$uri_data" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Eseye.php#L214-L284
eveseat/eseye
src/Eseye.php
Eseye.buildDataUri
public function buildDataUri(string $uri, array $data): Uri { // Create a query string for the URI. We automatically // include the datasource value from the configuration. $query_params = array_merge([ 'datasource' => $this->getConfiguration()->datasource, ], $this->getQueryString()); return Uri::fromParts([ 'scheme' => $this->getConfiguration()->esi_scheme, 'host' => $this->getConfiguration()->esi_host, 'port' => $this->getConfiguration()->esi_port, 'path' => rtrim($this->getVersion(), '/') . $this->mapDataToUri($uri, $data), 'query' => http_build_query($query_params), ]); }
php
public function buildDataUri(string $uri, array $data): Uri { // Create a query string for the URI. We automatically // include the datasource value from the configuration. $query_params = array_merge([ 'datasource' => $this->getConfiguration()->datasource, ], $this->getQueryString()); return Uri::fromParts([ 'scheme' => $this->getConfiguration()->esi_scheme, 'host' => $this->getConfiguration()->esi_host, 'port' => $this->getConfiguration()->esi_port, 'path' => rtrim($this->getVersion(), '/') . $this->mapDataToUri($uri, $data), 'query' => http_build_query($query_params), ]); }
[ "public", "function", "buildDataUri", "(", "string", "$", "uri", ",", "array", "$", "data", ")", ":", "Uri", "{", "// Create a query string for the URI. We automatically", "// include the datasource value from the configuration.", "$", "query_params", "=", "array_merge", "(...
@param string $uri @param array $data @return \GuzzleHttp\Psr7\Uri @throws \Seat\Eseye\Exceptions\UriDataMissingException @throws \Seat\Eseye\Exceptions\InvalidContainerDataException
[ "@param", "string", "$uri", "@param", "array", "$data" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Eseye.php#L336-L353
eveseat/eseye
src/Eseye.php
Eseye.setQueryString
public function setQueryString(array $query): self { foreach ($query as $key => $value) { if (is_array($value)) { $query[$key] = implode(',', $value); } } $this->query_string = array_merge($this->query_string, $query); return $this; }
php
public function setQueryString(array $query): self { foreach ($query as $key => $value) { if (is_array($value)) { $query[$key] = implode(',', $value); } } $this->query_string = array_merge($this->query_string, $query); return $this; }
[ "public", "function", "setQueryString", "(", "array", "$", "query", ")", ":", "self", "{", "foreach", "(", "$", "query", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "query", "[", "...
@param array $query @return \Seat\Eseye\Eseye
[ "@param", "array", "$query" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Eseye.php#L369-L381
eveseat/eseye
src/Eseye.php
Eseye.setVersion
public function setVersion(string $version) { if (substr($version, 0, 1) !== '/') $version = '/' . $version; $this->version = $version; return $this; }
php
public function setVersion(string $version) { if (substr($version, 0, 1) !== '/') $version = '/' . $version; $this->version = $version; return $this; }
[ "public", "function", "setVersion", "(", "string", "$", "version", ")", "{", "if", "(", "substr", "(", "$", "version", ",", "0", ",", "1", ")", "!==", "'/'", ")", "$", "version", "=", "'/'", ".", "$", "version", ";", "$", "this", "->", "version", ...
Set the version of the API endpoints base URI. @param string $version @return \Seat\Eseye\Eseye
[ "Set", "the", "version", "of", "the", "API", "endpoints", "base", "URI", "." ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Eseye.php#L401-L410
eveseat/eseye
src/Eseye.php
Eseye.mapDataToUri
private function mapDataToUri(string $uri, array $data): string { // Extract fields in curly braces. If there are fields, // replace the data with those in the URI if (preg_match_all('/{+(.*?)}/', $uri, $matches)) { if (empty($data)) throw new UriDataMissingException( 'The data array for the uri ' . $uri . ' is empty. Please provide data to use.'); foreach ($matches[1] as $match) { if (! array_key_exists($match, $data)) throw new UriDataMissingException( 'Data for ' . $match . ' is missing. Please provide this by setting a value ' . 'for ' . $match . '.'); $uri = str_replace('{' . $match . '}', $data[$match], $uri); } } return $uri; }
php
private function mapDataToUri(string $uri, array $data): string { // Extract fields in curly braces. If there are fields, // replace the data with those in the URI if (preg_match_all('/{+(.*?)}/', $uri, $matches)) { if (empty($data)) throw new UriDataMissingException( 'The data array for the uri ' . $uri . ' is empty. Please provide data to use.'); foreach ($matches[1] as $match) { if (! array_key_exists($match, $data)) throw new UriDataMissingException( 'Data for ' . $match . ' is missing. Please provide this by setting a value ' . 'for ' . $match . '.'); $uri = str_replace('{' . $match . '}', $data[$match], $uri); } } return $uri; }
[ "private", "function", "mapDataToUri", "(", "string", "$", "uri", ",", "array", "$", "data", ")", ":", "string", "{", "// Extract fields in curly braces. If there are fields,", "// replace the data with those in the URI", "if", "(", "preg_match_all", "(", "'/{+(.*?)}/'", ...
@param string $uri @param array $data @return string @throws \Seat\Eseye\Exceptions\UriDataMissingException
[ "@param", "string", "$uri", "@param", "array", "$data" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Eseye.php#L419-L442
eveseat/eseye
src/Eseye.php
Eseye.rawFetch
public function rawFetch(string $method, string $uri, array $body, array $headers = []) { return $this->getFetcher()->call($method, $uri, $body, $headers); }
php
public function rawFetch(string $method, string $uri, array $body, array $headers = []) { return $this->getFetcher()->call($method, $uri, $body, $headers); }
[ "public", "function", "rawFetch", "(", "string", "$", "method", ",", "string", "$", "uri", ",", "array", "$", "body", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "return", "$", "this", "->", "getFetcher", "(", ")", "->", "call", "(", "$"...
@param string $method @param string $uri @param array $body @param array $headers @return mixed @throws \Seat\Eseye\Exceptions\InvalidAuthenticationException @throws \Seat\Eseye\Exceptions\RequestFailedException @throws \Seat\Eseye\Exceptions\InvalidContainerDataException
[ "@param", "string", "$method", "@param", "string", "$uri", "@param", "array", "$body", "@param", "array", "$headers" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Eseye.php#L465-L469
eveseat/eseye
src/Access/CheckAccess.php
CheckAccess.can
public function can(string $method, string $uri, array $scopes): bool { if (! array_key_exists($uri, $this->scope_map[$method])) { Configuration::getInstance()->getLogger() ->warning('An unknown URI was called. Allowing ' . $uri); return true; } $required_scope = $this->scope_map[$method][$uri]; // Public scopes require no authentication! if ($required_scope == 'public') return true; if (! in_array($required_scope, $scopes)) return false; return true; }
php
public function can(string $method, string $uri, array $scopes): bool { if (! array_key_exists($uri, $this->scope_map[$method])) { Configuration::getInstance()->getLogger() ->warning('An unknown URI was called. Allowing ' . $uri); return true; } $required_scope = $this->scope_map[$method][$uri]; // Public scopes require no authentication! if ($required_scope == 'public') return true; if (! in_array($required_scope, $scopes)) return false; return true; }
[ "public", "function", "can", "(", "string", "$", "method", ",", "string", "$", "uri", ",", "array", "$", "scopes", ")", ":", "bool", "{", "if", "(", "!", "array_key_exists", "(", "$", "uri", ",", "$", "this", "->", "scope_map", "[", "$", "method", ...
@param string $method @param string $uri @param array $scopes @return bool|mixed @throws \Seat\Eseye\Exceptions\InvalidContainerDataException
[ "@param", "string", "$method", "@param", "string", "$uri", "@param", "array", "$scopes" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Access/CheckAccess.php#L265-L286
eveseat/eseye
src/Cache/RedisCache.php
RedisCache.set
public function set(string $uri, string $query, EsiResponse $data) { $this->redis->set($this->buildCacheKey($uri, $query), serialize($data)); }
php
public function set(string $uri, string $query, EsiResponse $data) { $this->redis->set($this->buildCacheKey($uri, $query), serialize($data)); }
[ "public", "function", "set", "(", "string", "$", "uri", ",", "string", "$", "query", ",", "EsiResponse", "$", "data", ")", "{", "$", "this", "->", "redis", "->", "set", "(", "$", "this", "->", "buildCacheKey", "(", "$", "uri", ",", "$", "query", ")...
@param string $uri @param string $query @param \Seat\Eseye\Containers\EsiResponse $data @return void
[ "@param", "string", "$uri", "@param", "string", "$query", "@param", "\\", "Seat", "\\", "Eseye", "\\", "Containers", "\\", "EsiResponse", "$data" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Cache/RedisCache.php#L76-L80
eveseat/eseye
src/Cache/RedisCache.php
RedisCache.get
public function get(string $uri, string $query = '') { if (! $this->has($uri, $query)) return false; $data = unserialize($this->redis ->get($this->buildCacheKey($uri, $query))); // If the cached entry is expired and does not have any ETag, remove it. if ($data->expired() && ! $data->hasHeader('ETag')) { $this->forget($uri, $query); return false; } return $data; }
php
public function get(string $uri, string $query = '') { if (! $this->has($uri, $query)) return false; $data = unserialize($this->redis ->get($this->buildCacheKey($uri, $query))); // If the cached entry is expired and does not have any ETag, remove it. if ($data->expired() && ! $data->hasHeader('ETag')) { $this->forget($uri, $query); return false; } return $data; }
[ "public", "function", "get", "(", "string", "$", "uri", ",", "string", "$", "query", "=", "''", ")", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "uri", ",", "$", "query", ")", ")", "return", "false", ";", "$", "data", "=", "unseria...
@param string $uri @param string $query @return mixed
[ "@param", "string", "$uri", "@param", "string", "$query" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Cache/RedisCache.php#L103-L121
eveseat/eseye
src/Cache/RedisCache.php
RedisCache.has
public function has(string $uri, string $query = ''): bool { return $this->redis->exists($this->buildCacheKey($uri, $query)); }
php
public function has(string $uri, string $query = ''): bool { return $this->redis->exists($this->buildCacheKey($uri, $query)); }
[ "public", "function", "has", "(", "string", "$", "uri", ",", "string", "$", "query", "=", "''", ")", ":", "bool", "{", "return", "$", "this", "->", "redis", "->", "exists", "(", "$", "this", "->", "buildCacheKey", "(", "$", "uri", ",", "$", "query"...
@param string $uri @param string $query @return bool|mixed
[ "@param", "string", "$uri", "@param", "string", "$query" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Cache/RedisCache.php#L129-L133
eveseat/eseye
src/Cache/RedisCache.php
RedisCache.forget
public function forget(string $uri, string $query = '') { return $this->redis->del([$this->buildCacheKey($uri, $query)]); }
php
public function forget(string $uri, string $query = '') { return $this->redis->del([$this->buildCacheKey($uri, $query)]); }
[ "public", "function", "forget", "(", "string", "$", "uri", ",", "string", "$", "query", "=", "''", ")", "{", "return", "$", "this", "->", "redis", "->", "del", "(", "[", "$", "this", "->", "buildCacheKey", "(", "$", "uri", ",", "$", "query", ")", ...
@param string $uri @param string $query @return mixed
[ "@param", "string", "$uri", "@param", "string", "$query" ]
train
https://github.com/eveseat/eseye/blob/55a90ccd49b548cb417ace32075a9188b8d9c1af/src/Cache/RedisCache.php#L141-L145
fgrosse/PHPASN1
lib/ASN1/OID.php
OID.getName
public static function getName($oidString, $loadFromWeb = true) { switch ($oidString) { case self::RSA_ENCRYPTION: return 'RSA Encryption'; case self::MD5_WITH_RSA_ENCRYPTION: return 'MD5 with RSA Encryption'; case self::SHA1_WITH_RSA_SIGNATURE: return 'SHA-1 with RSA Signature'; case self::PKCS9_EMAIL: return 'PKCS #9 Email Address'; case self::PKCS9_UNSTRUCTURED_NAME: return 'PKCS #9 Unstructured Name'; case self::PKCS9_CONTENT_TYPE: return 'PKCS #9 Content Type'; case self::PKCS9_MESSAGE_DIGEST: return 'PKCS #9 Message Digest'; case self::PKCS9_SIGNING_TIME: return 'PKCS #9 Signing Time'; case self::COMMON_NAME: return 'Common Name'; case self::SURNAME: return 'Surname'; case self::SERIAL_NUMBER: return 'Serial Number'; case self::COUNTRY_NAME: return 'Country Name'; case self::LOCALITY_NAME: return 'Locality Name'; case self::STATE_OR_PROVINCE_NAME: return 'State or Province Name'; case self::STREET_ADDRESS: return 'Street Address'; case self::ORGANIZATION_NAME: return 'Organization Name'; case self::OU_NAME: return 'Organization Unit Name'; case self::TITLE: return 'Title'; case self::DESCRIPTION: return 'Description'; case self::POSTAL_ADDRESS: return 'Postal Address'; case self::POSTAL_CODE: return 'Postal Code'; case self::AUTHORITY_REVOCATION_LIST: return 'Authority Revocation List'; case self::CERT_EXT_SUBJECT_DIRECTORY_ATTR: return 'Subject directory attributes'; case self::CERT_EXT_SUBJECT_KEY_IDENTIFIER: return 'Subject key identifier'; case self::CERT_EXT_KEY_USAGE: return 'Key usage certificate extension'; case self::CERT_EXT_PRIVATE_KEY_USAGE_PERIOD: return 'Private key usage'; case self::CERT_EXT_SUBJECT_ALT_NAME: return 'Subject alternative name (SAN)'; case self::CERT_EXT_ISSUER_ALT_NAME: return 'Issuer alternative name'; case self::CERT_EXT_BASIC_CONSTRAINTS: return 'Basic constraints'; case self::CERT_EXT_CRL_NUMBER: return 'CRL number'; case self::CERT_EXT_REASON_CODE: return 'Reason code'; case self::CERT_EXT_INVALIDITY_DATE: return 'Invalidity code'; case self::CERT_EXT_DELTA_CRL_INDICATOR: return 'Delta CRL indicator'; case self::CERT_EXT_ISSUING_DIST_POINT: return 'Issuing distribution point'; case self::CERT_EXT_CERT_ISSUER: return 'Certificate issuer'; case self::CERT_EXT_NAME_CONSTRAINTS: return 'Name constraints'; case self::CERT_EXT_CRL_DISTRIBUTION_POINTS: return 'CRL distribution points'; case self::CERT_EXT_CERT_POLICIES: return 'Certificate policies '; case self::CERT_EXT_AUTHORITY_KEY_IDENTIFIER: return 'Authority key identifier'; case self::CERT_EXT_EXTENDED_KEY_USAGE: return 'Extended key usage'; case self::AUTHORITY_INFORMATION_ACCESS: return 'Certificate Authority Information Access (AIA)'; default: if ($loadFromWeb) { return self::loadFromWeb($oidString); } else { return $oidString; } } }
php
public static function getName($oidString, $loadFromWeb = true) { switch ($oidString) { case self::RSA_ENCRYPTION: return 'RSA Encryption'; case self::MD5_WITH_RSA_ENCRYPTION: return 'MD5 with RSA Encryption'; case self::SHA1_WITH_RSA_SIGNATURE: return 'SHA-1 with RSA Signature'; case self::PKCS9_EMAIL: return 'PKCS #9 Email Address'; case self::PKCS9_UNSTRUCTURED_NAME: return 'PKCS #9 Unstructured Name'; case self::PKCS9_CONTENT_TYPE: return 'PKCS #9 Content Type'; case self::PKCS9_MESSAGE_DIGEST: return 'PKCS #9 Message Digest'; case self::PKCS9_SIGNING_TIME: return 'PKCS #9 Signing Time'; case self::COMMON_NAME: return 'Common Name'; case self::SURNAME: return 'Surname'; case self::SERIAL_NUMBER: return 'Serial Number'; case self::COUNTRY_NAME: return 'Country Name'; case self::LOCALITY_NAME: return 'Locality Name'; case self::STATE_OR_PROVINCE_NAME: return 'State or Province Name'; case self::STREET_ADDRESS: return 'Street Address'; case self::ORGANIZATION_NAME: return 'Organization Name'; case self::OU_NAME: return 'Organization Unit Name'; case self::TITLE: return 'Title'; case self::DESCRIPTION: return 'Description'; case self::POSTAL_ADDRESS: return 'Postal Address'; case self::POSTAL_CODE: return 'Postal Code'; case self::AUTHORITY_REVOCATION_LIST: return 'Authority Revocation List'; case self::CERT_EXT_SUBJECT_DIRECTORY_ATTR: return 'Subject directory attributes'; case self::CERT_EXT_SUBJECT_KEY_IDENTIFIER: return 'Subject key identifier'; case self::CERT_EXT_KEY_USAGE: return 'Key usage certificate extension'; case self::CERT_EXT_PRIVATE_KEY_USAGE_PERIOD: return 'Private key usage'; case self::CERT_EXT_SUBJECT_ALT_NAME: return 'Subject alternative name (SAN)'; case self::CERT_EXT_ISSUER_ALT_NAME: return 'Issuer alternative name'; case self::CERT_EXT_BASIC_CONSTRAINTS: return 'Basic constraints'; case self::CERT_EXT_CRL_NUMBER: return 'CRL number'; case self::CERT_EXT_REASON_CODE: return 'Reason code'; case self::CERT_EXT_INVALIDITY_DATE: return 'Invalidity code'; case self::CERT_EXT_DELTA_CRL_INDICATOR: return 'Delta CRL indicator'; case self::CERT_EXT_ISSUING_DIST_POINT: return 'Issuing distribution point'; case self::CERT_EXT_CERT_ISSUER: return 'Certificate issuer'; case self::CERT_EXT_NAME_CONSTRAINTS: return 'Name constraints'; case self::CERT_EXT_CRL_DISTRIBUTION_POINTS: return 'CRL distribution points'; case self::CERT_EXT_CERT_POLICIES: return 'Certificate policies '; case self::CERT_EXT_AUTHORITY_KEY_IDENTIFIER: return 'Authority key identifier'; case self::CERT_EXT_EXTENDED_KEY_USAGE: return 'Extended key usage'; case self::AUTHORITY_INFORMATION_ACCESS: return 'Certificate Authority Information Access (AIA)'; default: if ($loadFromWeb) { return self::loadFromWeb($oidString); } else { return $oidString; } } }
[ "public", "static", "function", "getName", "(", "$", "oidString", ",", "$", "loadFromWeb", "=", "true", ")", "{", "switch", "(", "$", "oidString", ")", "{", "case", "self", "::", "RSA_ENCRYPTION", ":", "return", "'RSA Encryption'", ";", "case", "self", "::...
Returns the name of the given object identifier. Some OIDs are saved as class constants in this class. If the wanted oidString is not among them, this method will query http://oid-info.com for the right name. This behavior can be suppressed by setting the second method parameter to false. @param string $oidString @param bool $loadFromWeb @see self::loadFromWeb($oidString) @return string
[ "Returns", "the", "name", "of", "the", "given", "object", "identifier", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/OID.php#L78-L174
fgrosse/PHPASN1
lib/ASN1/Base128.php
Base128.encode
public static function encode($value) { $value = BigInteger::create($value); $octets = chr($value->modulus(0x80)->toInteger()); $value = $value->shiftRight(7); while ($value->compare(0) > 0) { $octets .= chr(0x80 | $value->modulus(0x80)->toInteger()); $value = $value->shiftRight(7); } return strrev($octets); }
php
public static function encode($value) { $value = BigInteger::create($value); $octets = chr($value->modulus(0x80)->toInteger()); $value = $value->shiftRight(7); while ($value->compare(0) > 0) { $octets .= chr(0x80 | $value->modulus(0x80)->toInteger()); $value = $value->shiftRight(7); } return strrev($octets); }
[ "public", "static", "function", "encode", "(", "$", "value", ")", "{", "$", "value", "=", "BigInteger", "::", "create", "(", "$", "value", ")", ";", "$", "octets", "=", "chr", "(", "$", "value", "->", "modulus", "(", "0x80", ")", "->", "toInteger", ...
@param int $value @return string
[ "@param", "int", "$value" ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Base128.php#L18-L30
fgrosse/PHPASN1
lib/ASN1/Base128.php
Base128.decode
public static function decode($octets) { $bitsPerOctet = 7; $value = BigInteger::create(0); $i = 0; while (true) { if (!isset($octets[$i])) { throw new InvalidArgumentException(sprintf('Malformed base-128 encoded value (0x%s).', strtoupper(bin2hex($octets)) ?: '0')); } $octet = ord($octets[$i++]); $l1 = $value->shiftLeft($bitsPerOctet); $r1 = $octet & 0x7f; $value = $l1->add($r1); if (0 === ($octet & 0x80)) { break; } } return (string)$value; }
php
public static function decode($octets) { $bitsPerOctet = 7; $value = BigInteger::create(0); $i = 0; while (true) { if (!isset($octets[$i])) { throw new InvalidArgumentException(sprintf('Malformed base-128 encoded value (0x%s).', strtoupper(bin2hex($octets)) ?: '0')); } $octet = ord($octets[$i++]); $l1 = $value->shiftLeft($bitsPerOctet); $r1 = $octet & 0x7f; $value = $l1->add($r1); if (0 === ($octet & 0x80)) { break; } } return (string)$value; }
[ "public", "static", "function", "decode", "(", "$", "octets", ")", "{", "$", "bitsPerOctet", "=", "7", ";", "$", "value", "=", "BigInteger", "::", "create", "(", "0", ")", ";", "$", "i", "=", "0", ";", "while", "(", "true", ")", "{", "if", "(", ...
@param string $octets @throws InvalidArgumentException if the given octets represent a malformed base-128 value or the decoded value would exceed the the maximum integer length @return int
[ "@param", "string", "$octets" ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Base128.php#L39-L62
fgrosse/PHPASN1
lib/ASN1/Universal/ObjectIdentifier.php
ObjectIdentifier.parseOid
protected static function parseOid(&$binaryData, &$offsetIndex, $octetsToRead) { $oid = ''; while ($octetsToRead > 0) { $octets = ''; do { if (0 === $octetsToRead) { throw new ParserException('Malformed ASN.1 Object Identifier', $offsetIndex - 1); } $octetsToRead--; $octet = $binaryData[$offsetIndex++]; $octets .= $octet; } while (ord($octet) & 0x80); $oid .= sprintf('%d.', Base128::decode($octets)); } // Remove trailing '.' return substr($oid, 0, -1) ?: ''; }
php
protected static function parseOid(&$binaryData, &$offsetIndex, $octetsToRead) { $oid = ''; while ($octetsToRead > 0) { $octets = ''; do { if (0 === $octetsToRead) { throw new ParserException('Malformed ASN.1 Object Identifier', $offsetIndex - 1); } $octetsToRead--; $octet = $binaryData[$offsetIndex++]; $octets .= $octet; } while (ord($octet) & 0x80); $oid .= sprintf('%d.', Base128::decode($octets)); } // Remove trailing '.' return substr($oid, 0, -1) ?: ''; }
[ "protected", "static", "function", "parseOid", "(", "&", "$", "binaryData", ",", "&", "$", "offsetIndex", ",", "$", "octetsToRead", ")", "{", "$", "oid", "=", "''", ";", "while", "(", "$", "octetsToRead", ">", "0", ")", "{", "$", "octets", "=", "''",...
Parses an object identifier except for the first octet, which is parsed differently. This way relative object identifiers can also be parsed using this. @param $binaryData @param $offsetIndex @param $octetsToRead @throws ParserException @return string
[ "Parses", "an", "object", "identifier", "except", "for", "the", "first", "octet", "which", "is", "parsed", "differently", ".", "This", "way", "relative", "object", "identifiers", "can", "also", "be", "parsed", "using", "this", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Universal/ObjectIdentifier.php#L115-L137
fgrosse/PHPASN1
lib/ASN1/ASNObject.php
ASNObject.getBinary
public function getBinary() { $result = $this->getIdentifier(); $result .= $this->createLengthPart(); $result .= $this->getEncodedValue(); return $result; }
php
public function getBinary() { $result = $this->getIdentifier(); $result .= $this->createLengthPart(); $result .= $this->getEncodedValue(); return $result; }
[ "public", "function", "getBinary", "(", ")", "{", "$", "result", "=", "$", "this", "->", "getIdentifier", "(", ")", ";", "$", "result", ".=", "$", "this", "->", "createLengthPart", "(", ")", ";", "$", "result", ".=", "$", "this", "->", "getEncodedValue...
Encode this object using DER encoding. @return string the full binary representation of the complete object
[ "Encode", "this", "object", "using", "DER", "encoding", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/ASNObject.php#L108-L115
fgrosse/PHPASN1
lib/ASN1/ASNObject.php
ASNObject.getObjectLength
public function getObjectLength() { $nrOfIdentifierOctets = strlen($this->getIdentifier()); $contentLength = $this->getContentLength(); $nrOfLengthOctets = $this->getNumberOfLengthOctets($contentLength); return $nrOfIdentifierOctets + $nrOfLengthOctets + $contentLength; }
php
public function getObjectLength() { $nrOfIdentifierOctets = strlen($this->getIdentifier()); $contentLength = $this->getContentLength(); $nrOfLengthOctets = $this->getNumberOfLengthOctets($contentLength); return $nrOfIdentifierOctets + $nrOfLengthOctets + $contentLength; }
[ "public", "function", "getObjectLength", "(", ")", "{", "$", "nrOfIdentifierOctets", "=", "strlen", "(", "$", "this", "->", "getIdentifier", "(", ")", ")", ";", "$", "contentLength", "=", "$", "this", "->", "getContentLength", "(", ")", ";", "$", "nrOfLeng...
Returns the length of the whole object (including the identifier and length octets).
[ "Returns", "the", "length", "of", "the", "whole", "object", "(", "including", "the", "identifier", "and", "length", "octets", ")", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/ASNObject.php#L172-L179
fgrosse/PHPASN1
lib/Utility/BigInteger.php
BigInteger.create
public static function create($val) { if (self::$_prefer) { switch (self::$_prefer) { case 'gmp': $ret = new BigIntegerGmp(); break; case 'bcmath': $ret = new BigIntegerBcmath(); break; default: throw new \UnexpectedValueException('Unknown number implementation: ' . self::$_prefer); } } else { // autodetect if (extension_loaded('gmp')) { $ret = new BigIntegerGmp(); } elseif (extension_loaded('bcmath')) { $ret = new BigIntegerBcmath(); } else { // TODO: potentially offer pure php implementation? throw new \RuntimeException('Requires GMP or bcmath extension.'); } } if (is_int($val)) { $ret->_fromInteger($val); } else { // convert to string, if not already one $val = (string)$val; // validate string if (!preg_match('/^-?[0-9]+$/', $val)) { throw new \InvalidArgumentException('Expects a string representation of an integer.'); } $ret->_fromString($val); } return $ret; }
php
public static function create($val) { if (self::$_prefer) { switch (self::$_prefer) { case 'gmp': $ret = new BigIntegerGmp(); break; case 'bcmath': $ret = new BigIntegerBcmath(); break; default: throw new \UnexpectedValueException('Unknown number implementation: ' . self::$_prefer); } } else { // autodetect if (extension_loaded('gmp')) { $ret = new BigIntegerGmp(); } elseif (extension_loaded('bcmath')) { $ret = new BigIntegerBcmath(); } else { // TODO: potentially offer pure php implementation? throw new \RuntimeException('Requires GMP or bcmath extension.'); } } if (is_int($val)) { $ret->_fromInteger($val); } else { // convert to string, if not already one $val = (string)$val; // validate string if (!preg_match('/^-?[0-9]+$/', $val)) { throw new \InvalidArgumentException('Expects a string representation of an integer.'); } $ret->_fromString($val); } return $ret; }
[ "public", "static", "function", "create", "(", "$", "val", ")", "{", "if", "(", "self", "::", "$", "_prefer", ")", "{", "switch", "(", "self", "::", "$", "_prefer", ")", "{", "case", "'gmp'", ":", "$", "ret", "=", "new", "BigIntegerGmp", "(", ")", ...
Create a BigInteger instance based off the base 10 string or an integer. @param string|int $val @return BigInteger @throws \InvalidArgumentException
[ "Create", "a", "BigInteger", "instance", "based", "off", "the", "base", "10", "string", "or", "an", "integer", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/Utility/BigInteger.php#L40-L83
fgrosse/PHPASN1
lib/ASN1/Construct.php
Construct.fromBinary
public static function fromBinary(&$binaryData, &$offsetIndex = 0) { $parsedObject = new static(); self::parseIdentifier($binaryData[$offsetIndex], $parsedObject->getType(), $offsetIndex++); $contentLength = self::parseContentLength($binaryData, $offsetIndex); $startIndex = $offsetIndex; $children = []; $octetsToRead = $contentLength; while ($octetsToRead > 0) { $newChild = ASNObject::fromBinary($binaryData, $offsetIndex); $octetsToRead -= $newChild->getObjectLength(); $children[] = $newChild; } if ($octetsToRead !== 0) { throw new ParserException("Sequence length incorrect", $startIndex); } $parsedObject->addChildren($children); $parsedObject->setContentLength($contentLength); return $parsedObject; }
php
public static function fromBinary(&$binaryData, &$offsetIndex = 0) { $parsedObject = new static(); self::parseIdentifier($binaryData[$offsetIndex], $parsedObject->getType(), $offsetIndex++); $contentLength = self::parseContentLength($binaryData, $offsetIndex); $startIndex = $offsetIndex; $children = []; $octetsToRead = $contentLength; while ($octetsToRead > 0) { $newChild = ASNObject::fromBinary($binaryData, $offsetIndex); $octetsToRead -= $newChild->getObjectLength(); $children[] = $newChild; } if ($octetsToRead !== 0) { throw new ParserException("Sequence length incorrect", $startIndex); } $parsedObject->addChildren($children); $parsedObject->setContentLength($contentLength); return $parsedObject; }
[ "public", "static", "function", "fromBinary", "(", "&", "$", "binaryData", ",", "&", "$", "offsetIndex", "=", "0", ")", "{", "$", "parsedObject", "=", "new", "static", "(", ")", ";", "self", "::", "parseIdentifier", "(", "$", "binaryData", "[", "$", "o...
@param string $binaryData @param int $offsetIndex @throws Exception\ParserException @return Construct|static
[ "@param", "string", "$binaryData", "@param", "int", "$offsetIndex" ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Construct.php#L157-L180
fgrosse/PHPASN1
lib/ASN1/Identifier.php
Identifier.create
public static function create($class, $isConstructed, $tagNumber) { if (!is_numeric($class) || $class < self::CLASS_UNIVERSAL || $class > self::CLASS_PRIVATE) { throw new Exception(sprintf('Invalid class %d given', $class)); } if (!is_bool($isConstructed)) { throw new Exception("\$isConstructed must be a boolean value ($isConstructed given)"); } $tagNumber = self::makeNumeric($tagNumber); if ($tagNumber < 0) { throw new Exception(sprintf('Invalid $tagNumber %d given. You can only use positive integers.', $tagNumber)); } if ($tagNumber < self::LONG_FORM) { return ($class << 6) | ($isConstructed << 5) | $tagNumber; } $firstOctet = ($class << 6) | ($isConstructed << 5) | self::LONG_FORM; // Tag numbers formatted in long form are base-128 encoded. See X.609#8.1.2.4 return chr($firstOctet).Base128::encode($tagNumber); }
php
public static function create($class, $isConstructed, $tagNumber) { if (!is_numeric($class) || $class < self::CLASS_UNIVERSAL || $class > self::CLASS_PRIVATE) { throw new Exception(sprintf('Invalid class %d given', $class)); } if (!is_bool($isConstructed)) { throw new Exception("\$isConstructed must be a boolean value ($isConstructed given)"); } $tagNumber = self::makeNumeric($tagNumber); if ($tagNumber < 0) { throw new Exception(sprintf('Invalid $tagNumber %d given. You can only use positive integers.', $tagNumber)); } if ($tagNumber < self::LONG_FORM) { return ($class << 6) | ($isConstructed << 5) | $tagNumber; } $firstOctet = ($class << 6) | ($isConstructed << 5) | self::LONG_FORM; // Tag numbers formatted in long form are base-128 encoded. See X.609#8.1.2.4 return chr($firstOctet).Base128::encode($tagNumber); }
[ "public", "static", "function", "create", "(", "$", "class", ",", "$", "isConstructed", ",", "$", "tagNumber", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "class", ")", "||", "$", "class", "<", "self", "::", "CLASS_UNIVERSAL", "||", "$", "class",...
Creates an identifier. Short form identifiers are returned as integers for BC, long form identifiers will be returned as a string of octets. @param int $class @param bool $isConstructed @param int $tagNumber @throws Exception if the given arguments are invalid @return int|string
[ "Creates", "an", "identifier", ".", "Short", "form", "identifiers", "are", "returned", "as", "integers", "for", "BC", "long", "form", "identifiers", "will", "be", "returned", "as", "a", "string", "of", "octets", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Identifier.php#L82-L105
fgrosse/PHPASN1
lib/ASN1/Identifier.php
Identifier.getName
public static function getName($identifier) { $identifierOctet = self::makeNumeric($identifier); $typeName = static::getShortName($identifier); if (($identifierOctet & self::LONG_FORM) < self::LONG_FORM) { $typeName = "ASN.1 {$typeName}"; } return $typeName; }
php
public static function getName($identifier) { $identifierOctet = self::makeNumeric($identifier); $typeName = static::getShortName($identifier); if (($identifierOctet & self::LONG_FORM) < self::LONG_FORM) { $typeName = "ASN.1 {$typeName}"; } return $typeName; }
[ "public", "static", "function", "getName", "(", "$", "identifier", ")", "{", "$", "identifierOctet", "=", "self", "::", "makeNumeric", "(", "$", "identifier", ")", ";", "$", "typeName", "=", "static", "::", "getShortName", "(", "$", "identifier", ")", ";",...
Return the name of the mapped ASN.1 type with a preceding "ASN.1 ". Example: ASN.1 Octet String @see Identifier::getShortName() @param int|string $identifier @return string
[ "Return", "the", "name", "of", "the", "mapped", "ASN", ".", "1", "type", "with", "a", "preceding", "ASN", ".", "1", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Identifier.php#L128-L139
fgrosse/PHPASN1
lib/ASN1/Identifier.php
Identifier.getShortName
public static function getShortName($identifier) { $identifierOctet = self::makeNumeric($identifier); switch ($identifierOctet) { case self::EOC: return 'End-of-contents octet'; case self::BOOLEAN: return 'Boolean'; case self::INTEGER: return 'Integer'; case self::BITSTRING: return 'Bit String'; case self::OCTETSTRING: return 'Octet String'; case self::NULL: return 'NULL'; case self::OBJECT_IDENTIFIER: return 'Object Identifier'; case self::OBJECT_DESCRIPTOR: return 'Object Descriptor'; case self::EXTERNAL: return 'External Type'; case self::REAL: return 'Real'; case self::ENUMERATED: return 'Enumerated'; case self::EMBEDDED_PDV: return 'Embedded PDV'; case self::UTF8_STRING: return 'UTF8 String'; case self::RELATIVE_OID: return 'Relative OID'; case self::SEQUENCE: return 'Sequence'; case self::SET: return 'Set'; case self::NUMERIC_STRING: return 'Numeric String'; case self::PRINTABLE_STRING: return 'Printable String'; case self::T61_STRING: return 'T61 String'; case self::VIDEOTEXT_STRING: return 'Videotext String'; case self::IA5_STRING: return 'IA5 String'; case self::UTC_TIME: return 'UTC Time'; case self::GENERALIZED_TIME: return 'Generalized Time'; case self::GRAPHIC_STRING: return 'Graphic String'; case self::VISIBLE_STRING: return 'Visible String'; case self::GENERAL_STRING: return 'General String'; case self::UNIVERSAL_STRING: return 'Universal String'; case self::CHARACTER_STRING: return 'Character String'; case self::BMP_STRING: return 'BMP String'; case 0x0E: return 'RESERVED (0x0E)'; case 0x0F: return 'RESERVED (0x0F)'; case self::LONG_FORM: default: $classDescription = self::getClassDescription($identifier); if (is_int($identifier)) { $identifier = chr($identifier); } return "$classDescription (0x".strtoupper(bin2hex($identifier)).')'; } }
php
public static function getShortName($identifier) { $identifierOctet = self::makeNumeric($identifier); switch ($identifierOctet) { case self::EOC: return 'End-of-contents octet'; case self::BOOLEAN: return 'Boolean'; case self::INTEGER: return 'Integer'; case self::BITSTRING: return 'Bit String'; case self::OCTETSTRING: return 'Octet String'; case self::NULL: return 'NULL'; case self::OBJECT_IDENTIFIER: return 'Object Identifier'; case self::OBJECT_DESCRIPTOR: return 'Object Descriptor'; case self::EXTERNAL: return 'External Type'; case self::REAL: return 'Real'; case self::ENUMERATED: return 'Enumerated'; case self::EMBEDDED_PDV: return 'Embedded PDV'; case self::UTF8_STRING: return 'UTF8 String'; case self::RELATIVE_OID: return 'Relative OID'; case self::SEQUENCE: return 'Sequence'; case self::SET: return 'Set'; case self::NUMERIC_STRING: return 'Numeric String'; case self::PRINTABLE_STRING: return 'Printable String'; case self::T61_STRING: return 'T61 String'; case self::VIDEOTEXT_STRING: return 'Videotext String'; case self::IA5_STRING: return 'IA5 String'; case self::UTC_TIME: return 'UTC Time'; case self::GENERALIZED_TIME: return 'Generalized Time'; case self::GRAPHIC_STRING: return 'Graphic String'; case self::VISIBLE_STRING: return 'Visible String'; case self::GENERAL_STRING: return 'General String'; case self::UNIVERSAL_STRING: return 'Universal String'; case self::CHARACTER_STRING: return 'Character String'; case self::BMP_STRING: return 'BMP String'; case 0x0E: return 'RESERVED (0x0E)'; case 0x0F: return 'RESERVED (0x0F)'; case self::LONG_FORM: default: $classDescription = self::getClassDescription($identifier); if (is_int($identifier)) { $identifier = chr($identifier); } return "$classDescription (0x".strtoupper(bin2hex($identifier)).')'; } }
[ "public", "static", "function", "getShortName", "(", "$", "identifier", ")", "{", "$", "identifierOctet", "=", "self", "::", "makeNumeric", "(", "$", "identifier", ")", ";", "switch", "(", "$", "identifierOctet", ")", "{", "case", "self", "::", "EOC", ":",...
Return the short version of the type name. If the given identifier octet can be mapped to a known universal type this will return its name. Else Identifier::getClassDescription() is used to retrieve information about the identifier. @see Identifier::getName() @see Identifier::getClassDescription() @param int|string $identifier @return string
[ "Return", "the", "short", "version", "of", "the", "type", "name", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Identifier.php#L155-L234
fgrosse/PHPASN1
lib/ASN1/Identifier.php
Identifier.getClassDescription
public static function getClassDescription($identifier) { $identifierOctet = self::makeNumeric($identifier); if (self::isConstructed($identifierOctet)) { $classDescription = 'Constructed '; } else { $classDescription = 'Primitive '; } $classBits = $identifierOctet >> 6; switch ($classBits) { case self::CLASS_UNIVERSAL: $classDescription .= 'universal'; break; case self::CLASS_APPLICATION: $classDescription .= 'application'; break; case self::CLASS_CONTEXT_SPECIFIC: $tagNumber = self::getTagNumber($identifier); $classDescription = "[$tagNumber] Context-specific"; break; case self::CLASS_PRIVATE: $classDescription .= 'private'; break; default: return "INVALID IDENTIFIER OCTET: {$identifierOctet}"; } return $classDescription; }
php
public static function getClassDescription($identifier) { $identifierOctet = self::makeNumeric($identifier); if (self::isConstructed($identifierOctet)) { $classDescription = 'Constructed '; } else { $classDescription = 'Primitive '; } $classBits = $identifierOctet >> 6; switch ($classBits) { case self::CLASS_UNIVERSAL: $classDescription .= 'universal'; break; case self::CLASS_APPLICATION: $classDescription .= 'application'; break; case self::CLASS_CONTEXT_SPECIFIC: $tagNumber = self::getTagNumber($identifier); $classDescription = "[$tagNumber] Context-specific"; break; case self::CLASS_PRIVATE: $classDescription .= 'private'; break; default: return "INVALID IDENTIFIER OCTET: {$identifierOctet}"; } return $classDescription; }
[ "public", "static", "function", "getClassDescription", "(", "$", "identifier", ")", "{", "$", "identifierOctet", "=", "self", "::", "makeNumeric", "(", "$", "identifier", ")", ";", "if", "(", "self", "::", "isConstructed", "(", "$", "identifierOctet", ")", "...
Returns a textual description of the information encoded in a given identifier octet. The first three (most significant) bytes are evaluated to determine if this is a constructed or primitive type and if it is either universal, application, context-specific or private. Example: Constructed context-specific Primitive universal @param int|string $identifier @return string
[ "Returns", "a", "textual", "description", "of", "the", "information", "encoded", "in", "a", "given", "identifier", "octet", "." ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Identifier.php#L251-L281
fgrosse/PHPASN1
lib/ASN1/Identifier.php
Identifier.getTagNumber
public static function getTagNumber($identifier) { $firstOctet = self::makeNumeric($identifier); $tagNumber = $firstOctet & self::LONG_FORM; if ($tagNumber < self::LONG_FORM) { return $tagNumber; } if (is_numeric($identifier)) { $identifier = chr($identifier); } return Base128::decode(substr($identifier, 1)); }
php
public static function getTagNumber($identifier) { $firstOctet = self::makeNumeric($identifier); $tagNumber = $firstOctet & self::LONG_FORM; if ($tagNumber < self::LONG_FORM) { return $tagNumber; } if (is_numeric($identifier)) { $identifier = chr($identifier); } return Base128::decode(substr($identifier, 1)); }
[ "public", "static", "function", "getTagNumber", "(", "$", "identifier", ")", "{", "$", "firstOctet", "=", "self", "::", "makeNumeric", "(", "$", "identifier", ")", ";", "$", "tagNumber", "=", "$", "firstOctet", "&", "self", "::", "LONG_FORM", ";", "if", ...
@param int|string $identifier @return int
[ "@param", "int|string", "$identifier" ]
train
https://github.com/fgrosse/PHPASN1/blob/7ebf2a09084a7bbdb7b879c66fdf7ad80461bbe8/lib/ASN1/Identifier.php#L288-L301
ddeboer/data-import
src/Writer/ConsoleProgressWriter.php
ConsoleProgressWriter.prepare
public function prepare() { $this->progress = new ProgressBar($this->output, $this->reader->count()); $this->progress->setFormat($this->verbosity); $this->progress->setRedrawFrequency($this->redrawFrequency); $this->progress->start(); }
php
public function prepare() { $this->progress = new ProgressBar($this->output, $this->reader->count()); $this->progress->setFormat($this->verbosity); $this->progress->setRedrawFrequency($this->redrawFrequency); $this->progress->start(); }
[ "public", "function", "prepare", "(", ")", "{", "$", "this", "->", "progress", "=", "new", "ProgressBar", "(", "$", "this", "->", "output", ",", "$", "this", "->", "reader", "->", "count", "(", ")", ")", ";", "$", "this", "->", "progress", "->", "s...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/ConsoleProgressWriter.php#L63-L69
ddeboer/data-import
src/Reader/CsvReader.php
CsvReader.current
public function current() { // If the CSV has no column headers just return the line if (empty($this->columnHeaders)) { return $this->file->current(); } // Since the CSV has column headers use them to construct an associative array for the columns in this line do { $line = $this->file->current(); // In non-strict mode pad/slice the line to match the column headers if (!$this->isStrict()) { if ($this->headersCount > count($line)) { $line = array_pad($line, $this->headersCount, null); // Line too short } else { $line = array_slice($line, 0, $this->headersCount); // Line too long } } // See if values for duplicate headers should be merged if (self::DUPLICATE_HEADERS_MERGE === $this->duplicateHeadersFlag) { $line = $this->mergeDuplicates($line); } // Count the number of elements in both: they must be equal. if (count($this->columnHeaders) === count($line)) { return array_combine(array_keys($this->columnHeaders), $line); } // They are not equal, so log the row as error and skip it. if ($this->valid()) { $this->errors[$this->key()] = $line; $this->next(); } } while($this->valid()); return null; }
php
public function current() { // If the CSV has no column headers just return the line if (empty($this->columnHeaders)) { return $this->file->current(); } // Since the CSV has column headers use them to construct an associative array for the columns in this line do { $line = $this->file->current(); // In non-strict mode pad/slice the line to match the column headers if (!$this->isStrict()) { if ($this->headersCount > count($line)) { $line = array_pad($line, $this->headersCount, null); // Line too short } else { $line = array_slice($line, 0, $this->headersCount); // Line too long } } // See if values for duplicate headers should be merged if (self::DUPLICATE_HEADERS_MERGE === $this->duplicateHeadersFlag) { $line = $this->mergeDuplicates($line); } // Count the number of elements in both: they must be equal. if (count($this->columnHeaders) === count($line)) { return array_combine(array_keys($this->columnHeaders), $line); } // They are not equal, so log the row as error and skip it. if ($this->valid()) { $this->errors[$this->key()] = $line; $this->next(); } } while($this->valid()); return null; }
[ "public", "function", "current", "(", ")", "{", "// If the CSV has no column headers just return the line", "if", "(", "empty", "(", "$", "this", "->", "columnHeaders", ")", ")", "{", "return", "$", "this", "->", "file", "->", "current", "(", ")", ";", "}", ...
Return the current row as an array If a header row has been set, an associative array will be returned @return array
[ "Return", "the", "current", "row", "as", "an", "array" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/CsvReader.php#L106-L144
ddeboer/data-import
src/Reader/CsvReader.php
CsvReader.setColumnHeaders
public function setColumnHeaders(array $columnHeaders) { $this->columnHeaders = array_count_values($columnHeaders); $this->headersCount = count($columnHeaders); }
php
public function setColumnHeaders(array $columnHeaders) { $this->columnHeaders = array_count_values($columnHeaders); $this->headersCount = count($columnHeaders); }
[ "public", "function", "setColumnHeaders", "(", "array", "$", "columnHeaders", ")", "{", "$", "this", "->", "columnHeaders", "=", "array_count_values", "(", "$", "columnHeaders", ")", ";", "$", "this", "->", "headersCount", "=", "count", "(", "$", "columnHeader...
Set column headers @param array $columnHeaders
[ "Set", "column", "headers" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/CsvReader.php#L161-L165
ddeboer/data-import
src/Reader/CsvReader.php
CsvReader.setHeaderRowNumber
public function setHeaderRowNumber($rowNumber, $duplicates = null) { $this->duplicateHeadersFlag = $duplicates; $this->headerRowNumber = $rowNumber; $headers = $this->readHeaderRow($rowNumber); $this->setColumnHeaders($headers); }
php
public function setHeaderRowNumber($rowNumber, $duplicates = null) { $this->duplicateHeadersFlag = $duplicates; $this->headerRowNumber = $rowNumber; $headers = $this->readHeaderRow($rowNumber); $this->setColumnHeaders($headers); }
[ "public", "function", "setHeaderRowNumber", "(", "$", "rowNumber", ",", "$", "duplicates", "=", "null", ")", "{", "$", "this", "->", "duplicateHeadersFlag", "=", "$", "duplicates", ";", "$", "this", "->", "headerRowNumber", "=", "$", "rowNumber", ";", "$", ...
Set header row number @param integer $rowNumber Number of the row that contains column header names @param integer $duplicates How to handle duplicates (optional). One of: - CsvReader::DUPLICATE_HEADERS_INCREMENT; increments duplicates (dup, dup1, dup2 etc.) - CsvReader::DUPLICATE_HEADERS_MERGE; merges values for duplicate headers into an array (dup => [value1, value2, value3]) @throws DuplicateHeadersException If duplicate headers are encountered and no duplicate handling has been specified
[ "Set", "header", "row", "number" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/CsvReader.php#L182-L189
ddeboer/data-import
src/Reader/CsvReader.php
CsvReader.rewind
public function rewind() { $this->file->rewind(); if (null !== $this->headerRowNumber) { $this->file->seek($this->headerRowNumber + 1); } }
php
public function rewind() { $this->file->rewind(); if (null !== $this->headerRowNumber) { $this->file->seek($this->headerRowNumber + 1); } }
[ "public", "function", "rewind", "(", ")", "{", "$", "this", "->", "file", "->", "rewind", "(", ")", ";", "if", "(", "null", "!==", "$", "this", "->", "headerRowNumber", ")", "{", "$", "this", "->", "file", "->", "seek", "(", "$", "this", "->", "h...
Rewind the file pointer If a header row has been set, the pointer is set just below the header row. That way, when you iterate over the rows, that header row is skipped.
[ "Rewind", "the", "file", "pointer" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/CsvReader.php#L198-L204
ddeboer/data-import
src/Reader/CsvReader.php
CsvReader.count
public function count() { if (null === $this->count) { $position = $this->key(); $this->count = iterator_count($this); $this->seek($position); } return $this->count; }
php
public function count() { if (null === $this->count) { $position = $this->key(); $this->count = iterator_count($this); $this->seek($position); } return $this->count; }
[ "public", "function", "count", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "count", ")", "{", "$", "position", "=", "$", "this", "->", "key", "(", ")", ";", "$", "this", "->", "count", "=", "iterator_count", "(", "$", "this", ")",...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/CsvReader.php#L209-L220
ddeboer/data-import
src/Reader/CsvReader.php
CsvReader.readHeaderRow
protected function readHeaderRow($rowNumber) { $this->file->seek($rowNumber); $headers = $this->file->current(); // Test for duplicate column headers $diff = array_diff_assoc($headers, array_unique($headers)); if (count($diff) > 0) { switch ($this->duplicateHeadersFlag) { case self::DUPLICATE_HEADERS_INCREMENT: $headers = $this->incrementHeaders($headers); // Fall through case self::DUPLICATE_HEADERS_MERGE: break; default: throw new DuplicateHeadersException($diff); } } return $headers; }
php
protected function readHeaderRow($rowNumber) { $this->file->seek($rowNumber); $headers = $this->file->current(); // Test for duplicate column headers $diff = array_diff_assoc($headers, array_unique($headers)); if (count($diff) > 0) { switch ($this->duplicateHeadersFlag) { case self::DUPLICATE_HEADERS_INCREMENT: $headers = $this->incrementHeaders($headers); // Fall through case self::DUPLICATE_HEADERS_MERGE: break; default: throw new DuplicateHeadersException($diff); } } return $headers; }
[ "protected", "function", "readHeaderRow", "(", "$", "rowNumber", ")", "{", "$", "this", "->", "file", "->", "seek", "(", "$", "rowNumber", ")", ";", "$", "headers", "=", "$", "this", "->", "file", "->", "current", "(", ")", ";", "// Test for duplicate co...
Read header row from CSV file @param integer $rowNumber Row number @return array @throws DuplicateHeadersException
[ "Read", "header", "row", "from", "CSV", "file" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/CsvReader.php#L330-L350
ddeboer/data-import
src/Reader/CsvReader.php
CsvReader.incrementHeaders
protected function incrementHeaders(array $headers) { $incrementedHeaders = []; foreach (array_count_values($headers) as $header => $count) { if ($count > 1) { $incrementedHeaders[] = $header; for ($i = 1; $i < $count; $i++) { $incrementedHeaders[] = $header . $i; } } else { $incrementedHeaders[] = $header; } } return $incrementedHeaders; }
php
protected function incrementHeaders(array $headers) { $incrementedHeaders = []; foreach (array_count_values($headers) as $header => $count) { if ($count > 1) { $incrementedHeaders[] = $header; for ($i = 1; $i < $count; $i++) { $incrementedHeaders[] = $header . $i; } } else { $incrementedHeaders[] = $header; } } return $incrementedHeaders; }
[ "protected", "function", "incrementHeaders", "(", "array", "$", "headers", ")", "{", "$", "incrementedHeaders", "=", "[", "]", ";", "foreach", "(", "array_count_values", "(", "$", "headers", ")", "as", "$", "header", "=>", "$", "count", ")", "{", "if", "...
Add an increment to duplicate headers So the following line: |duplicate|duplicate|duplicate| |first |second |third | Yields value: $duplicate => 'first', $duplicate1 => 'second', $duplicate2 => 'third' @param array $headers @return array
[ "Add", "an", "increment", "to", "duplicate", "headers" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/CsvReader.php#L366-L381
ddeboer/data-import
src/Reader/CsvReader.php
CsvReader.mergeDuplicates
protected function mergeDuplicates(array $line) { $values = []; $i = 0; foreach ($this->columnHeaders as $count) { if (1 === $count) { $values[] = $line[$i]; } else { $values[] = array_slice($line, $i, $count); } $i += $count; } return $values; }
php
protected function mergeDuplicates(array $line) { $values = []; $i = 0; foreach ($this->columnHeaders as $count) { if (1 === $count) { $values[] = $line[$i]; } else { $values[] = array_slice($line, $i, $count); } $i += $count; } return $values; }
[ "protected", "function", "mergeDuplicates", "(", "array", "$", "line", ")", "{", "$", "values", "=", "[", "]", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "this", "->", "columnHeaders", "as", "$", "count", ")", "{", "if", "(", "1", "===", ...
Merges values for duplicate headers into an array So the following line: |duplicate|duplicate|duplicate| |first |second |third | Yields value: $duplicate => ['first', 'second', 'third'] @param array $line @return array
[ "Merges", "values", "for", "duplicate", "headers", "into", "an", "array" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/CsvReader.php#L397-L413
ddeboer/data-import
src/Writer/ExcelWriter.php
ExcelWriter.prepare
public function prepare() { $reader = PHPExcel_IOFactory::createReader($this->type); if ($reader->canRead($this->filename)) { $this->excel = $reader->load($this->filename); } else { $this->excel = new PHPExcel(); if(null !== $this->sheet && !$this->excel->sheetNameExists($this->sheet)) { $this->excel->removeSheetByIndex(0); } } if (null !== $this->sheet) { if (!$this->excel->sheetNameExists($this->sheet)) { $this->excel->createSheet()->setTitle($this->sheet); } $this->excel->setActiveSheetIndexByName($this->sheet); } }
php
public function prepare() { $reader = PHPExcel_IOFactory::createReader($this->type); if ($reader->canRead($this->filename)) { $this->excel = $reader->load($this->filename); } else { $this->excel = new PHPExcel(); if(null !== $this->sheet && !$this->excel->sheetNameExists($this->sheet)) { $this->excel->removeSheetByIndex(0); } } if (null !== $this->sheet) { if (!$this->excel->sheetNameExists($this->sheet)) { $this->excel->createSheet()->setTitle($this->sheet); } $this->excel->setActiveSheetIndexByName($this->sheet); } }
[ "public", "function", "prepare", "(", ")", "{", "$", "reader", "=", "PHPExcel_IOFactory", "::", "createReader", "(", "$", "this", "->", "type", ")", ";", "if", "(", "$", "reader", "->", "canRead", "(", "$", "this", "->", "filename", ")", ")", "{", "$...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/ExcelWriter.php#L63-L82
ddeboer/data-import
src/Writer/ExcelWriter.php
ExcelWriter.writeItem
public function writeItem(array $item) { $count = count($item); if ($this->prependHeaderRow && 1 == $this->row) { $headers = array_keys($item); for ($i = 0; $i < $count; $i++) { $this->excel->getActiveSheet()->setCellValueByColumnAndRow($i, $this->row, $headers[$i]); } $this->row++; } $values = array_values($item); for ($i = 0; $i < $count; $i++) { $this->excel->getActiveSheet()->setCellValueByColumnAndRow($i, $this->row, $values[$i]); } $this->row++; }
php
public function writeItem(array $item) { $count = count($item); if ($this->prependHeaderRow && 1 == $this->row) { $headers = array_keys($item); for ($i = 0; $i < $count; $i++) { $this->excel->getActiveSheet()->setCellValueByColumnAndRow($i, $this->row, $headers[$i]); } $this->row++; } $values = array_values($item); for ($i = 0; $i < $count; $i++) { $this->excel->getActiveSheet()->setCellValueByColumnAndRow($i, $this->row, $values[$i]); } $this->row++; }
[ "public", "function", "writeItem", "(", "array", "$", "item", ")", "{", "$", "count", "=", "count", "(", "$", "item", ")", ";", "if", "(", "$", "this", "->", "prependHeaderRow", "&&", "1", "==", "$", "this", "->", "row", ")", "{", "$", "headers", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/ExcelWriter.php#L87-L107
ddeboer/data-import
src/Writer/ExcelWriter.php
ExcelWriter.finish
public function finish() { $writer = \PHPExcel_IOFactory::createWriter($this->excel, $this->type); $writer->save($this->filename); }
php
public function finish() { $writer = \PHPExcel_IOFactory::createWriter($this->excel, $this->type); $writer->save($this->filename); }
[ "public", "function", "finish", "(", ")", "{", "$", "writer", "=", "\\", "PHPExcel_IOFactory", "::", "createWriter", "(", "$", "this", "->", "excel", ",", "$", "this", "->", "type", ")", ";", "$", "writer", "->", "save", "(", "$", "this", "->", "file...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/ExcelWriter.php#L112-L116
ddeboer/data-import
src/Reader/DbalReader.php
DbalReader.setSql
public function setSql($sql, array $params = []) { $this->sql = (string) $sql; $this->setSqlParameters($params); }
php
public function setSql($sql, array $params = []) { $this->sql = (string) $sql; $this->setSqlParameters($params); }
[ "public", "function", "setSql", "(", "$", "sql", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "this", "->", "sql", "=", "(", "string", ")", "$", "sql", ";", "$", "this", "->", "setSqlParameters", "(", "$", "params", ")", ";", "}" ]
Set Query string with Parameters @param string $sql @param array $params
[ "Set", "Query", "string", "with", "Parameters" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/DbalReader.php#L105-L110
ddeboer/data-import
src/Reader/DbalReader.php
DbalReader.setSqlParameters
public function setSqlParameters(array $params) { $this->params = $params; $this->stmt = null; $this->rowCount = null; }
php
public function setSqlParameters(array $params) { $this->params = $params; $this->stmt = null; $this->rowCount = null; }
[ "public", "function", "setSqlParameters", "(", "array", "$", "params", ")", "{", "$", "this", "->", "params", "=", "$", "params", ";", "$", "this", "->", "stmt", "=", "null", ";", "$", "this", "->", "rowCount", "=", "null", ";", "}" ]
Set SQL parameters @param array $params
[ "Set", "SQL", "parameters" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/DbalReader.php#L117-L123
ddeboer/data-import
src/Reader/DbalReader.php
DbalReader.next
public function next() { $this->key++; $this->data = $this->stmt->fetch(\PDO::FETCH_ASSOC); }
php
public function next() { $this->key++; $this->data = $this->stmt->fetch(\PDO::FETCH_ASSOC); }
[ "public", "function", "next", "(", ")", "{", "$", "this", "->", "key", "++", ";", "$", "this", "->", "data", "=", "$", "this", "->", "stmt", "->", "fetch", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/DbalReader.php#L140-L144
ddeboer/data-import
src/Reader/DbalReader.php
DbalReader.rewind
public function rewind() { if (null === $this->stmt) { $this->stmt = $this->prepare($this->sql, $this->params); } if (0 !== $this->key) { $this->stmt->execute(); $this->data = $this->stmt->fetch(\PDO::FETCH_ASSOC); $this->key = 0; } }
php
public function rewind() { if (null === $this->stmt) { $this->stmt = $this->prepare($this->sql, $this->params); } if (0 !== $this->key) { $this->stmt->execute(); $this->data = $this->stmt->fetch(\PDO::FETCH_ASSOC); $this->key = 0; } }
[ "public", "function", "rewind", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "stmt", ")", "{", "$", "this", "->", "stmt", "=", "$", "this", "->", "prepare", "(", "$", "this", "->", "sql", ",", "$", "this", "->", "params", ")", ";...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/DbalReader.php#L169-L179
ddeboer/data-import
src/Reader/DbalReader.php
DbalReader.count
public function count() { if (null === $this->rowCount) { if ($this->rowCountCalculated) { $this->doCalcRowCount(); } else { if (null === $this->stmt) { $this->rewind(); } $this->rowCount = $this->stmt->rowCount(); } } return $this->rowCount; }
php
public function count() { if (null === $this->rowCount) { if ($this->rowCountCalculated) { $this->doCalcRowCount(); } else { if (null === $this->stmt) { $this->rewind(); } $this->rowCount = $this->stmt->rowCount(); } } return $this->rowCount; }
[ "public", "function", "count", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "rowCount", ")", "{", "if", "(", "$", "this", "->", "rowCountCalculated", ")", "{", "$", "this", "->", "doCalcRowCount", "(", ")", ";", "}", "else", "{", "if...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/DbalReader.php#L184-L198
ddeboer/data-import
src/Reader/DbalReader.php
DbalReader.prepare
private function prepare($sql, array $params) { $statement = $this->connection->prepare($sql); foreach ($params as $key => $value) { $statement->bindValue($key, $value); } return $statement; }
php
private function prepare($sql, array $params) { $statement = $this->connection->prepare($sql); foreach ($params as $key => $value) { $statement->bindValue($key, $value); } return $statement; }
[ "private", "function", "prepare", "(", "$", "sql", ",", "array", "$", "params", ")", "{", "$", "statement", "=", "$", "this", "->", "connection", "->", "prepare", "(", "$", "sql", ")", ";", "foreach", "(", "$", "params", "as", "$", "key", "=>", "$"...
Prepare given statement @param string $sql @param array $params @return Statement
[ "Prepare", "given", "statement" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/DbalReader.php#L216-L224
ddeboer/data-import
src/Step/ValidatorStep.php
ValidatorStep.add
public function add($field, Constraint $constraint) { if (!isset($this->constraints[$field])) { $this->constraints['fields'][$field] = []; } $this->constraints['fields'][$field][] = $constraint; return $this; }
php
public function add($field, Constraint $constraint) { if (!isset($this->constraints[$field])) { $this->constraints['fields'][$field] = []; } $this->constraints['fields'][$field][] = $constraint; return $this; }
[ "public", "function", "add", "(", "$", "field", ",", "Constraint", "$", "constraint", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "constraints", "[", "$", "field", "]", ")", ")", "{", "$", "this", "->", "constraints", "[", "'fields'", ...
@param string $field @param Constraint $constraint @return $this
[ "@param", "string", "$field", "@param", "Constraint", "$constraint" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Step/ValidatorStep.php#L60-L69
ddeboer/data-import
src/Step/ValidatorStep.php
ValidatorStep.addOption
public function addOption($option, $optionValue) { if (!in_array($option, $this->possibleOptions)) { return; } $this->constraints[$option] = $optionValue; }
php
public function addOption($option, $optionValue) { if (!in_array($option, $this->possibleOptions)) { return; } $this->constraints[$option] = $optionValue; }
[ "public", "function", "addOption", "(", "$", "option", ",", "$", "optionValue", ")", "{", "if", "(", "!", "in_array", "(", "$", "option", ",", "$", "this", "->", "possibleOptions", ")", ")", "{", "return", ";", "}", "$", "this", "->", "constraints", ...
Add additional options for the constraints @param string $option @param $optionValue
[ "Add", "additional", "options", "for", "the", "constraints" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Step/ValidatorStep.php#L92-L99
ddeboer/data-import
src/Reader/ExcelReader.php
ExcelReader.current
public function current() { $row = $this->worksheet[$this->pointer]; // If the CSV has column headers, use them to construct an associative // array for the columns in this line if (!empty($this->columnHeaders)) { // Count the number of elements in both: they must be equal. // If not, ignore the row if (count($this->columnHeaders) == count($row)) { return array_combine(array_values($this->columnHeaders), $row); } } else { // Else just return the column values return $row; } }
php
public function current() { $row = $this->worksheet[$this->pointer]; // If the CSV has column headers, use them to construct an associative // array for the columns in this line if (!empty($this->columnHeaders)) { // Count the number of elements in both: they must be equal. // If not, ignore the row if (count($this->columnHeaders) == count($row)) { return array_combine(array_values($this->columnHeaders), $row); } } else { // Else just return the column values return $row; } }
[ "public", "function", "current", "(", ")", "{", "$", "row", "=", "$", "this", "->", "worksheet", "[", "$", "this", "->", "pointer", "]", ";", "// If the CSV has column headers, use them to construct an associative", "// array for the columns in this line", "if", "(", ...
Return the current row as an array If a header row has been set, an associative array will be returned @return array
[ "Return", "the", "current", "row", "as", "an", "array" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/ExcelReader.php#L75-L91
ddeboer/data-import
src/Reader/ExcelReader.php
ExcelReader.rewind
public function rewind() { if (null === $this->headerRowNumber) { $this->pointer = 0; } else { $this->pointer = $this->headerRowNumber + 1; } }
php
public function rewind() { if (null === $this->headerRowNumber) { $this->pointer = 0; } else { $this->pointer = $this->headerRowNumber + 1; } }
[ "public", "function", "rewind", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "headerRowNumber", ")", "{", "$", "this", "->", "pointer", "=", "0", ";", "}", "else", "{", "$", "this", "->", "pointer", "=", "$", "this", "->", "headerRow...
Rewind the file pointer If a header row has been set, the pointer is set just below the header row. That way, when you iterate over the rows, that header row is skipped.
[ "Rewind", "the", "file", "pointer" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/ExcelReader.php#L120-L127
ddeboer/data-import
src/Reader/ExcelReader.php
ExcelReader.setHeaderRowNumber
public function setHeaderRowNumber($rowNumber) { $this->headerRowNumber = $rowNumber; $this->columnHeaders = $this->worksheet[$rowNumber]; }
php
public function setHeaderRowNumber($rowNumber) { $this->headerRowNumber = $rowNumber; $this->columnHeaders = $this->worksheet[$rowNumber]; }
[ "public", "function", "setHeaderRowNumber", "(", "$", "rowNumber", ")", "{", "$", "this", "->", "headerRowNumber", "=", "$", "rowNumber", ";", "$", "this", "->", "columnHeaders", "=", "$", "this", "->", "worksheet", "[", "$", "rowNumber", "]", ";", "}" ]
Set header row number @param integer $rowNumber Number of the row that contains column header names
[ "Set", "header", "row", "number" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/ExcelReader.php#L134-L138
ddeboer/data-import
src/Reader/ExcelReader.php
ExcelReader.count
public function count() { $count = count($this->worksheet); if (null !== $this->headerRowNumber) { $count--; } return $count; }
php
public function count() { $count = count($this->worksheet); if (null !== $this->headerRowNumber) { $count--; } return $count; }
[ "public", "function", "count", "(", ")", "{", "$", "count", "=", "count", "(", "$", "this", "->", "worksheet", ")", ";", "if", "(", "null", "!==", "$", "this", "->", "headerRowNumber", ")", "{", "$", "count", "--", ";", "}", "return", "$", "count",...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/ExcelReader.php#L175-L183
ddeboer/data-import
src/Writer/CsvWriter.php
CsvWriter.writeItem
public function writeItem(array $item) { if ($this->prependHeaderRow && 1 == $this->row++) { $headers = array_keys($item); fputcsv($this->getStream(), $headers, $this->delimiter, $this->enclosure); } fputcsv($this->getStream(), $item, $this->delimiter, $this->enclosure); }
php
public function writeItem(array $item) { if ($this->prependHeaderRow && 1 == $this->row++) { $headers = array_keys($item); fputcsv($this->getStream(), $headers, $this->delimiter, $this->enclosure); } fputcsv($this->getStream(), $item, $this->delimiter, $this->enclosure); }
[ "public", "function", "writeItem", "(", "array", "$", "item", ")", "{", "if", "(", "$", "this", "->", "prependHeaderRow", "&&", "1", "==", "$", "this", "->", "row", "++", ")", "{", "$", "headers", "=", "array_keys", "(", "$", "item", ")", ";", "fpu...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/CsvWriter.php#L63-L71
ddeboer/data-import
src/Writer/ConsoleTableWriter.php
ConsoleTableWriter.writeItem
public function writeItem(array $item) { // Save first item to get keys to display at header if (is_null($this->firstItem)) { $this->firstItem = $item; } $this->table->addRow($item); }
php
public function writeItem(array $item) { // Save first item to get keys to display at header if (is_null($this->firstItem)) { $this->firstItem = $item; } $this->table->addRow($item); }
[ "public", "function", "writeItem", "(", "array", "$", "item", ")", "{", "// Save first item to get keys to display at header", "if", "(", "is_null", "(", "$", "this", "->", "firstItem", ")", ")", "{", "$", "this", "->", "firstItem", "=", "$", "item", ";", "}...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/ConsoleTableWriter.php#L43-L51
ddeboer/data-import
src/Writer/ConsoleTableWriter.php
ConsoleTableWriter.finish
public function finish() { $this->table->setHeaders(array_keys($this->firstItem)); $this->table->render(); $this->firstItem = null; }
php
public function finish() { $this->table->setHeaders(array_keys($this->firstItem)); $this->table->render(); $this->firstItem = null; }
[ "public", "function", "finish", "(", ")", "{", "$", "this", "->", "table", "->", "setHeaders", "(", "array_keys", "(", "$", "this", "->", "firstItem", ")", ")", ";", "$", "this", "->", "table", "->", "render", "(", ")", ";", "$", "this", "->", "fir...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/ConsoleTableWriter.php#L56-L61
ddeboer/data-import
src/ValueConverter/DateTimeToStringValueConverter.php
DateTimeToStringValueConverter.convert
public function convert($input) { if (!$input) { return; } if (!($input instanceof \DateTime)) { throw new UnexpectedValueException('Input must be DateTime object.'); } return $input->format($this->outputFormat); }
php
public function convert($input) { if (!$input) { return; } if (!($input instanceof \DateTime)) { throw new UnexpectedValueException('Input must be DateTime object.'); } return $input->format($this->outputFormat); }
[ "public", "function", "convert", "(", "$", "input", ")", "{", "if", "(", "!", "$", "input", ")", "{", "return", ";", "}", "if", "(", "!", "(", "$", "input", "instanceof", "\\", "DateTime", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(...
Convert string to date time object using specified format @param mixed $input @return \DateTime|string @throws UnexpectedValueException
[ "Convert", "string", "to", "date", "time", "object", "using", "specified", "format" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/ValueConverter/DateTimeToStringValueConverter.php#L36-L47
ddeboer/data-import
src/Writer/DoctrineWriter.php
DoctrineWriter.getNewInstance
protected function getNewInstance() { $className = $this->entityMetadata->getName(); if (class_exists($className) === false) { throw new \Exception('Unable to create new instance of ' . $className); } return new $className; }
php
protected function getNewInstance() { $className = $this->entityMetadata->getName(); if (class_exists($className) === false) { throw new \Exception('Unable to create new instance of ' . $className); } return new $className; }
[ "protected", "function", "getNewInstance", "(", ")", "{", "$", "className", "=", "$", "this", "->", "entityMetadata", "->", "getName", "(", ")", ";", "if", "(", "class_exists", "(", "$", "className", ")", "===", "false", ")", "{", "throw", "new", "\\", ...
Return a new instance of the entity @return object
[ "Return", "a", "new", "instance", "of", "the", "entity" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/DoctrineWriter.php#L136-L145
ddeboer/data-import
src/Writer/DoctrineWriter.php
DoctrineWriter.setValue
protected function setValue($entity, $value, $setter) { if (method_exists($entity, $setter)) { $entity->$setter($value); } }
php
protected function setValue($entity, $value, $setter) { if (method_exists($entity, $setter)) { $entity->$setter($value); } }
[ "protected", "function", "setValue", "(", "$", "entity", ",", "$", "value", ",", "$", "setter", ")", "{", "if", "(", "method_exists", "(", "$", "entity", ",", "$", "setter", ")", ")", "{", "$", "entity", "->", "$", "setter", "(", "$", "value", ")",...
Call a setter of the entity @param object $entity @param mixed $value @param string $setter
[ "Call", "a", "setter", "of", "the", "entity" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/DoctrineWriter.php#L154-L159
ddeboer/data-import
src/Writer/DoctrineWriter.php
DoctrineWriter.writeItem
public function writeItem(array $item) { $entity = $this->findOrCreateItem($item); $this->loadAssociationObjectsToEntity($item, $entity); $this->updateEntity($item, $entity); $this->entityManager->persist($entity); }
php
public function writeItem(array $item) { $entity = $this->findOrCreateItem($item); $this->loadAssociationObjectsToEntity($item, $entity); $this->updateEntity($item, $entity); $this->entityManager->persist($entity); }
[ "public", "function", "writeItem", "(", "array", "$", "item", ")", "{", "$", "entity", "=", "$", "this", "->", "findOrCreateItem", "(", "$", "item", ")", ";", "$", "this", "->", "loadAssociationObjectsToEntity", "(", "$", "item", ",", "$", "entity", ")",...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/DoctrineWriter.php#L175-L183
ddeboer/data-import
src/Writer/DoctrineWriter.php
DoctrineWriter.loadAssociationObjectsToEntity
protected function loadAssociationObjectsToEntity(array $item, $entity) { foreach ($this->entityMetadata->getAssociationMappings() as $associationMapping) { $value = null; if (isset($item[$associationMapping['fieldName']]) && !is_object($item[$associationMapping['fieldName']])) { $value = $this->entityManager->getReference($associationMapping['targetEntity'], $item[$associationMapping['fieldName']]); } if (null === $value) { continue; } $setter = 'set' . ucfirst($associationMapping['fieldName']); $this->setValue($entity, $value, $setter); } }
php
protected function loadAssociationObjectsToEntity(array $item, $entity) { foreach ($this->entityMetadata->getAssociationMappings() as $associationMapping) { $value = null; if (isset($item[$associationMapping['fieldName']]) && !is_object($item[$associationMapping['fieldName']])) { $value = $this->entityManager->getReference($associationMapping['targetEntity'], $item[$associationMapping['fieldName']]); } if (null === $value) { continue; } $setter = 'set' . ucfirst($associationMapping['fieldName']); $this->setValue($entity, $value, $setter); } }
[ "protected", "function", "loadAssociationObjectsToEntity", "(", "array", "$", "item", ",", "$", "entity", ")", "{", "foreach", "(", "$", "this", "->", "entityMetadata", "->", "getAssociationMappings", "(", ")", "as", "$", "associationMapping", ")", "{", "$", "...
Add the associated objects in case the item have for persist its relation @param array $item @param object $entity
[ "Add", "the", "associated", "objects", "in", "case", "the", "item", "have", "for", "persist", "its", "relation" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/DoctrineWriter.php#L219-L235
ddeboer/data-import
src/Writer/DoctrineWriter.php
DoctrineWriter.truncateTable
protected function truncateTable() { $tableName = $this->entityMetadata->table['name']; $connection = $this->entityManager->getConnection(); $query = $connection->getDatabasePlatform()->getTruncateTableSQL($tableName, true); $connection->executeQuery($query); }
php
protected function truncateTable() { $tableName = $this->entityMetadata->table['name']; $connection = $this->entityManager->getConnection(); $query = $connection->getDatabasePlatform()->getTruncateTableSQL($tableName, true); $connection->executeQuery($query); }
[ "protected", "function", "truncateTable", "(", ")", "{", "$", "tableName", "=", "$", "this", "->", "entityMetadata", "->", "table", "[", "'name'", "]", ";", "$", "connection", "=", "$", "this", "->", "entityManager", "->", "getConnection", "(", ")", ";", ...
Truncate the database table for this writer
[ "Truncate", "the", "database", "table", "for", "this", "writer" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/DoctrineWriter.php#L240-L246
ddeboer/data-import
src/Writer/DoctrineWriter.php
DoctrineWriter.disableLogging
protected function disableLogging() { $config = $this->entityManager->getConnection()->getConfiguration(); $this->originalLogger = $config->getSQLLogger(); $config->setSQLLogger(null); }
php
protected function disableLogging() { $config = $this->entityManager->getConnection()->getConfiguration(); $this->originalLogger = $config->getSQLLogger(); $config->setSQLLogger(null); }
[ "protected", "function", "disableLogging", "(", ")", "{", "$", "config", "=", "$", "this", "->", "entityManager", "->", "getConnection", "(", ")", "->", "getConfiguration", "(", ")", ";", "$", "this", "->", "originalLogger", "=", "$", "config", "->", "getS...
Disable Doctrine logging
[ "Disable", "Doctrine", "logging" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/DoctrineWriter.php#L251-L256
ddeboer/data-import
src/Writer/DoctrineWriter.php
DoctrineWriter.reEnableLogging
protected function reEnableLogging() { $config = $this->entityManager->getConnection()->getConfiguration(); $config->setSQLLogger($this->originalLogger); }
php
protected function reEnableLogging() { $config = $this->entityManager->getConnection()->getConfiguration(); $config->setSQLLogger($this->originalLogger); }
[ "protected", "function", "reEnableLogging", "(", ")", "{", "$", "config", "=", "$", "this", "->", "entityManager", "->", "getConnection", "(", ")", "->", "getConfiguration", "(", ")", ";", "$", "config", "->", "setSQLLogger", "(", "$", "this", "->", "origi...
Re-enable Doctrine logging
[ "Re", "-", "enable", "Doctrine", "logging" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/DoctrineWriter.php#L261-L265
ddeboer/data-import
src/Writer/DoctrineWriter.php
DoctrineWriter.findOrCreateItem
protected function findOrCreateItem(array $item) { $entity = null; // If the table was not truncated to begin with, find current entity // first if (false === $this->truncate) { if (!empty($this->lookupFields)) { $lookupConditions = array(); foreach ($this->lookupFields as $fieldName) { $lookupConditions[$fieldName] = $item[$fieldName]; } $entity = $this->entityRepository->findOneBy( $lookupConditions ); } else { $entity = $this->entityRepository->find(current($item)); } } if (!$entity) { return $this->getNewInstance(); } return $entity; }
php
protected function findOrCreateItem(array $item) { $entity = null; // If the table was not truncated to begin with, find current entity // first if (false === $this->truncate) { if (!empty($this->lookupFields)) { $lookupConditions = array(); foreach ($this->lookupFields as $fieldName) { $lookupConditions[$fieldName] = $item[$fieldName]; } $entity = $this->entityRepository->findOneBy( $lookupConditions ); } else { $entity = $this->entityRepository->find(current($item)); } } if (!$entity) { return $this->getNewInstance(); } return $entity; }
[ "protected", "function", "findOrCreateItem", "(", "array", "$", "item", ")", "{", "$", "entity", "=", "null", ";", "// If the table was not truncated to begin with, find current entity", "// first", "if", "(", "false", "===", "$", "this", "->", "truncate", ")", "{",...
Finds existing entity or create a new instance @param array $item
[ "Finds", "existing", "entity", "or", "create", "a", "new", "instance" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/DoctrineWriter.php#L272-L296
ddeboer/data-import
src/Step/ConverterStep.php
ConverterStep.process
public function process(&$item) { foreach ($this->converters as $converter) { $item = call_user_func($converter, $item); } return true; }
php
public function process(&$item) { foreach ($this->converters as $converter) { $item = call_user_func($converter, $item); } return true; }
[ "public", "function", "process", "(", "&", "$", "item", ")", "{", "foreach", "(", "$", "this", "->", "converters", "as", "$", "converter", ")", "{", "$", "item", "=", "call_user_func", "(", "$", "converter", ",", "$", "item", ")", ";", "}", "return",...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Step/ConverterStep.php#L43-L50
ddeboer/data-import
src/Reader/DoctrineReader.php
DoctrineReader.rewind
public function rewind() { if (!$this->iterableResult) { $query = $this->objectManager->createQuery( sprintf('SELECT o FROM %s o', $this->objectName) ); $this->iterableResult = $query->iterate([], Query::HYDRATE_ARRAY); } $this->iterableResult->rewind(); }
php
public function rewind() { if (!$this->iterableResult) { $query = $this->objectManager->createQuery( sprintf('SELECT o FROM %s o', $this->objectName) ); $this->iterableResult = $query->iterate([], Query::HYDRATE_ARRAY); } $this->iterableResult->rewind(); }
[ "public", "function", "rewind", "(", ")", "{", "if", "(", "!", "$", "this", "->", "iterableResult", ")", "{", "$", "query", "=", "$", "this", "->", "objectManager", "->", "createQuery", "(", "sprintf", "(", "'SELECT o FROM %s o'", ",", "$", "this", "->",...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/DoctrineReader.php#L85-L95
ddeboer/data-import
src/Reader/DoctrineReader.php
DoctrineReader.count
public function count() { $query = $this->objectManager->createQuery( sprintf('SELECT COUNT(o) FROM %s o', $this->objectName) ); return $query->getSingleScalarResult(); }
php
public function count() { $query = $this->objectManager->createQuery( sprintf('SELECT COUNT(o) FROM %s o', $this->objectName) ); return $query->getSingleScalarResult(); }
[ "public", "function", "count", "(", ")", "{", "$", "query", "=", "$", "this", "->", "objectManager", "->", "createQuery", "(", "sprintf", "(", "'SELECT COUNT(o) FROM %s o'", ",", "$", "this", "->", "objectName", ")", ")", ";", "return", "$", "query", "->",...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/DoctrineReader.php#L100-L107
ddeboer/data-import
src/Reader/PdoReader.php
PdoReader.getFields
public function getFields() { if ($this->statement->execute()) { // Statement executed successfully // Grab the first row to find keys $row = $this->statement->fetch(\PDO::FETCH_ASSOC); // Return field keys, or empty array no rows remain return array_keys($row ? $row : []); } else { // If the statement errors return empty return []; } }
php
public function getFields() { if ($this->statement->execute()) { // Statement executed successfully // Grab the first row to find keys $row = $this->statement->fetch(\PDO::FETCH_ASSOC); // Return field keys, or empty array no rows remain return array_keys($row ? $row : []); } else { // If the statement errors return empty return []; } }
[ "public", "function", "getFields", "(", ")", "{", "if", "(", "$", "this", "->", "statement", "->", "execute", "(", ")", ")", "{", "// Statement executed successfully", "// Grab the first row to find keys", "$", "row", "=", "$", "this", "->", "statement", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/PdoReader.php#L50-L62
ddeboer/data-import
src/Reader/PdoReader.php
PdoReader.loadData
protected function loadData() { if (null === $this->data) { $this->statement->execute(); $this->data = $this->statement->fetchAll(\PDO::FETCH_ASSOC); } }
php
protected function loadData() { if (null === $this->data) { $this->statement->execute(); $this->data = $this->statement->fetchAll(\PDO::FETCH_ASSOC); } }
[ "protected", "function", "loadData", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "data", ")", "{", "$", "this", "->", "statement", "->", "execute", "(", ")", ";", "$", "this", "->", "data", "=", "$", "this", "->", "statement", "->",...
Load data if it hasn't been loaded yet
[ "Load", "data", "if", "it", "hasn", "t", "been", "loaded", "yet" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/PdoReader.php#L121-L127
ddeboer/data-import
src/Writer/PdoWriter.php
PdoWriter.writeItem
public function writeItem(array $item) { if (null === $this->statement) { try { $this->statement = $this->pdo->prepare(sprintf( 'INSERT INTO %s (%s) VALUES (%s)', $this->tableName, implode(',', array_keys($item)), substr(str_repeat('?,', count($item)), 0, -1) )); } catch (\PDOException $e) { throw new WriterException('Failed to send query', null, $e); } } $this->stack[] = array_values($item); }
php
public function writeItem(array $item) { if (null === $this->statement) { try { $this->statement = $this->pdo->prepare(sprintf( 'INSERT INTO %s (%s) VALUES (%s)', $this->tableName, implode(',', array_keys($item)), substr(str_repeat('?,', count($item)), 0, -1) )); } catch (\PDOException $e) { throw new WriterException('Failed to send query', null, $e); } } $this->stack[] = array_values($item); }
[ "public", "function", "writeItem", "(", "array", "$", "item", ")", "{", "if", "(", "null", "===", "$", "this", "->", "statement", ")", "{", "try", "{", "$", "this", "->", "statement", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "sprintf", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Writer/PdoWriter.php#L66-L82
ddeboer/data-import
src/Step/FilterStep.php
FilterStep.add
public function add(callable $filter, $priority = null) { $this->filters->insert($filter, $priority); return $this; }
php
public function add(callable $filter, $priority = null) { $this->filters->insert($filter, $priority); return $this; }
[ "public", "function", "add", "(", "callable", "$", "filter", ",", "$", "priority", "=", "null", ")", "{", "$", "this", "->", "filters", "->", "insert", "(", "$", "filter", ",", "$", "priority", ")", ";", "return", "$", "this", ";", "}" ]
@param callable $filter @param integer $priority @return $this
[ "@param", "callable", "$filter", "@param", "integer", "$priority" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Step/FilterStep.php#L28-L33
ddeboer/data-import
src/Step/FilterStep.php
FilterStep.process
public function process(&$item) { foreach (clone $this->filters as $filter) { if (false === call_user_func($filter, $item)) { return false; } } return true; }
php
public function process(&$item) { foreach (clone $this->filters as $filter) { if (false === call_user_func($filter, $item)) { return false; } } return true; }
[ "public", "function", "process", "(", "&", "$", "item", ")", "{", "foreach", "(", "clone", "$", "this", "->", "filters", "as", "$", "filter", ")", "{", "if", "(", "false", "===", "call_user_func", "(", "$", "filter", ",", "$", "item", ")", ")", "{"...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Step/FilterStep.php#L38-L47
ddeboer/data-import
src/Reader/Factory/CsvReaderFactory.php
CsvReaderFactory.getReader
public function getReader(\SplFileObject $file) { $reader = new CsvReader($file, $this->delimiter, $this->enclosure, $this->escape); if (null !== $this->headerRowNumber) { $reader->setHeaderRowNumber($this->headerRowNumber); } $reader->setStrict($this->strict); return $reader; }
php
public function getReader(\SplFileObject $file) { $reader = new CsvReader($file, $this->delimiter, $this->enclosure, $this->escape); if (null !== $this->headerRowNumber) { $reader->setHeaderRowNumber($this->headerRowNumber); } $reader->setStrict($this->strict); return $reader; }
[ "public", "function", "getReader", "(", "\\", "SplFileObject", "$", "file", ")", "{", "$", "reader", "=", "new", "CsvReader", "(", "$", "file", ",", "$", "this", "->", "delimiter", ",", "$", "this", "->", "enclosure", ",", "$", "this", "->", "escape", ...
@param \SplFileObject $file @return CsvReader
[ "@param", "\\", "SplFileObject", "$file" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Reader/Factory/CsvReaderFactory.php#L65-L75
ddeboer/data-import
src/Workflow/StepAggregator.php
StepAggregator.addStep
public function addStep(Step $step, $priority = null) { $priority = null === $priority && $step instanceof PriorityStep ? $step->getPriority() : $priority; $priority = null === $priority ? 0 : $priority; $this->steps->insert($step, $priority); return $this; }
php
public function addStep(Step $step, $priority = null) { $priority = null === $priority && $step instanceof PriorityStep ? $step->getPriority() : $priority; $priority = null === $priority ? 0 : $priority; $this->steps->insert($step, $priority); return $this; }
[ "public", "function", "addStep", "(", "Step", "$", "step", ",", "$", "priority", "=", "null", ")", "{", "$", "priority", "=", "null", "===", "$", "priority", "&&", "$", "step", "instanceof", "PriorityStep", "?", "$", "step", "->", "getPriority", "(", "...
Add a step to the current workflow @param Step $step @param integer|null $priority @return $this
[ "Add", "a", "step", "to", "the", "current", "workflow" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Workflow/StepAggregator.php#L81-L89
ddeboer/data-import
src/Workflow/StepAggregator.php
StepAggregator.process
public function process() { $count = 0; $exceptions = new \SplObjectStorage(); $startTime = new \DateTime; foreach ($this->writers as $writer) { $writer->prepare(); } if (is_callable('pcntl_signal')) { pcntl_signal(SIGTERM, array($this, 'stop')); pcntl_signal(SIGINT, array($this, 'stop')); } // Read all items foreach ($this->reader as $index => $item) { if (is_callable('pcntl_signal_dispatch')) { pcntl_signal_dispatch(); } if ($this->shouldStop) { break; } try { foreach (clone $this->steps as $step) { if (false === $step->process($item)) { continue 2; } } if (!is_array($item) && !($item instanceof \ArrayAccess && $item instanceof \Traversable)) { throw new UnexpectedTypeException($item, 'array'); } foreach ($this->writers as $writer) { $writer->writeItem($item); } } catch(Exception $e) { if (!$this->skipItemOnFailure) { throw $e; } $exceptions->attach($e, $index); $this->logger->error($e->getMessage()); } $count++; } foreach ($this->writers as $writer) { $writer->finish(); } return new Result($this->name, $startTime, new \DateTime, $count, $exceptions); }
php
public function process() { $count = 0; $exceptions = new \SplObjectStorage(); $startTime = new \DateTime; foreach ($this->writers as $writer) { $writer->prepare(); } if (is_callable('pcntl_signal')) { pcntl_signal(SIGTERM, array($this, 'stop')); pcntl_signal(SIGINT, array($this, 'stop')); } // Read all items foreach ($this->reader as $index => $item) { if (is_callable('pcntl_signal_dispatch')) { pcntl_signal_dispatch(); } if ($this->shouldStop) { break; } try { foreach (clone $this->steps as $step) { if (false === $step->process($item)) { continue 2; } } if (!is_array($item) && !($item instanceof \ArrayAccess && $item instanceof \Traversable)) { throw new UnexpectedTypeException($item, 'array'); } foreach ($this->writers as $writer) { $writer->writeItem($item); } } catch(Exception $e) { if (!$this->skipItemOnFailure) { throw $e; } $exceptions->attach($e, $index); $this->logger->error($e->getMessage()); } $count++; } foreach ($this->writers as $writer) { $writer->finish(); } return new Result($this->name, $startTime, new \DateTime, $count, $exceptions); }
[ "public", "function", "process", "(", ")", "{", "$", "count", "=", "0", ";", "$", "exceptions", "=", "new", "\\", "SplObjectStorage", "(", ")", ";", "$", "startTime", "=", "new", "\\", "DateTime", ";", "foreach", "(", "$", "this", "->", "writers", "a...
{@inheritdoc}
[ "{" ]
train
https://github.com/ddeboer/data-import/blob/1b8f2e6f5731a21206cb8656334574b9be71d30a/src/Workflow/StepAggregator.php#L108-L165
fntneves/laravel-transactional-events
src/Neves/Events/EventServiceProvider.php
EventServiceProvider.register
public function register() { $this->mergeConfigFrom( __DIR__.'/../../config/transactional-events.php', 'transactional-events' ); if (! $this->app['config']->get('transactional-events.enable')) { return; } $this->app->afterResolving('db', function ($connectionResolver) { $eventDispatcher = $this->app->make(EventDispatcher::class); $this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) { $dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher); $dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional')); $dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded')); return $dispatcher; }); }); }
php
public function register() { $this->mergeConfigFrom( __DIR__.'/../../config/transactional-events.php', 'transactional-events' ); if (! $this->app['config']->get('transactional-events.enable')) { return; } $this->app->afterResolving('db', function ($connectionResolver) { $eventDispatcher = $this->app->make(EventDispatcher::class); $this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) { $dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher); $dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional')); $dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded')); return $dispatcher; }); }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "mergeConfigFrom", "(", "__DIR__", ".", "'/../../config/transactional-events.php'", ",", "'transactional-events'", ")", ";", "if", "(", "!", "$", "this", "->", "app", "[", "'config'", "]", "->...
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/EventServiceProvider.php#L15-L36
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.dispatch
public function dispatch($event, $payload = [], $halt = false) { $connection = $this->connectionResolver->connection(); // If halt is specified, then automatically dispatches the event // to the original dispatcher. This happens because the caller // is waiting for the result of the listeners of this event. if ($halt || ! $this->isTransactionalEvent($connection, $event)) { return $this->dispatcher->dispatch($event, $payload, $halt); } $this->addPendingEvent($connection, $event, $payload); }
php
public function dispatch($event, $payload = [], $halt = false) { $connection = $this->connectionResolver->connection(); // If halt is specified, then automatically dispatches the event // to the original dispatcher. This happens because the caller // is waiting for the result of the listeners of this event. if ($halt || ! $this->isTransactionalEvent($connection, $event)) { return $this->dispatcher->dispatch($event, $payload, $halt); } $this->addPendingEvent($connection, $event, $payload); }
[ "public", "function", "dispatch", "(", "$", "event", ",", "$", "payload", "=", "[", "]", ",", "$", "halt", "=", "false", ")", "{", "$", "connection", "=", "$", "this", "->", "connectionResolver", "->", "connection", "(", ")", ";", "// If halt is specifie...
Dispatch an event and call the listeners. @param string|object $event @param mixed $payload @param bool $halt @return array|null
[ "Dispatch", "an", "event", "and", "call", "the", "listeners", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L84-L96
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.commit
public function commit(ConnectionInterface $connection) { // We decrement the transaction level and prevent events to be dispatched // while comitting nested transactions, so no transient state is saved. // Only dispatch events right after the outer transaction commits. $this->transactionLevel--; if (! $this->isPrepared($connection) || $this->transactionLevel > 0) { return; } $this->dispatchPendingEvents($connection); }
php
public function commit(ConnectionInterface $connection) { // We decrement the transaction level and prevent events to be dispatched // while comitting nested transactions, so no transient state is saved. // Only dispatch events right after the outer transaction commits. $this->transactionLevel--; if (! $this->isPrepared($connection) || $this->transactionLevel > 0) { return; } $this->dispatchPendingEvents($connection); }
[ "public", "function", "commit", "(", "ConnectionInterface", "$", "connection", ")", "{", "// We decrement the transaction level and prevent events to be dispatched", "// while comitting nested transactions, so no transient state is saved.", "// Only dispatch events right after the outer transa...
Flush all pending events. @param \Illuminate\Database\ConnectionInterface $connection @return void
[ "Flush", "all", "pending", "events", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L104-L115
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.prepareTransaction
protected function prepareTransaction($connection) { $connectionId = $connection->getName(); $this->transactionLevel = $this->transactionLevel > 0 ? $this->transactionLevel + 1 : 1; // Now we prepare a new array level for this transaction in the current // transaction level. It allows nested transactions to rollback and // their events discarded without affecting previous transactions. $this->pendingEvents[$connectionId][$this->transactionLevel][] = []; }
php
protected function prepareTransaction($connection) { $connectionId = $connection->getName(); $this->transactionLevel = $this->transactionLevel > 0 ? $this->transactionLevel + 1 : 1; // Now we prepare a new array level for this transaction in the current // transaction level. It allows nested transactions to rollback and // their events discarded without affecting previous transactions. $this->pendingEvents[$connectionId][$this->transactionLevel][] = []; }
[ "protected", "function", "prepareTransaction", "(", "$", "connection", ")", "{", "$", "connectionId", "=", "$", "connection", "->", "getName", "(", ")", ";", "$", "this", "->", "transactionLevel", "=", "$", "this", "->", "transactionLevel", ">", "0", "?", ...
Prepare to store events for the current transaction. @param \Illuminate\Database\ConnectionInterface $connection @return void
[ "Prepare", "to", "store", "events", "for", "the", "current", "transaction", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L123-L132
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.addPendingEvent
protected function addPendingEvent($connection, $event, $payload) { $connectionId = $connection->getName(); $transactionLevel = $this->transactionLevel; $eventData = [ 'event' => $event, 'payload' => is_object($payload) ? clone $payload : $payload, ]; $transactionLevelEvents = &$this->pendingEvents[$connectionId][$transactionLevel]; $transactionLevelEvents[count($transactionLevelEvents) - 1][] = $eventData; }
php
protected function addPendingEvent($connection, $event, $payload) { $connectionId = $connection->getName(); $transactionLevel = $this->transactionLevel; $eventData = [ 'event' => $event, 'payload' => is_object($payload) ? clone $payload : $payload, ]; $transactionLevelEvents = &$this->pendingEvents[$connectionId][$transactionLevel]; $transactionLevelEvents[count($transactionLevelEvents) - 1][] = $eventData; }
[ "protected", "function", "addPendingEvent", "(", "$", "connection", ",", "$", "event", ",", "$", "payload", ")", "{", "$", "connectionId", "=", "$", "connection", "->", "getName", "(", ")", ";", "$", "transactionLevel", "=", "$", "this", "->", "transaction...
Add a transactional event waiting for transaction to commit. @param \Illuminate\Database\ConnectionInterface $connection @param string|object $event @param mixed $payload @return void
[ "Add", "a", "transactional", "event", "waiting", "for", "transaction", "to", "commit", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L142-L153
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.dispatchPendingEvents
protected function dispatchPendingEvents(ConnectionInterface $connection) { $connectionId = $connection->getName(); $consumingEvents = $this->pendingEvents[$connectionId]; unset($this->pendingEvents[$connectionId]); foreach ($consumingEvents as $transactionsEvents) { foreach ($transactionsEvents as $transactionEvents) { foreach ($transactionEvents as $event) { $this->dispatcher->dispatch($event['event'], $event['payload']); } } } }
php
protected function dispatchPendingEvents(ConnectionInterface $connection) { $connectionId = $connection->getName(); $consumingEvents = $this->pendingEvents[$connectionId]; unset($this->pendingEvents[$connectionId]); foreach ($consumingEvents as $transactionsEvents) { foreach ($transactionsEvents as $transactionEvents) { foreach ($transactionEvents as $event) { $this->dispatcher->dispatch($event['event'], $event['payload']); } } } }
[ "protected", "function", "dispatchPendingEvents", "(", "ConnectionInterface", "$", "connection", ")", "{", "$", "connectionId", "=", "$", "connection", "->", "getName", "(", ")", ";", "$", "consumingEvents", "=", "$", "this", "->", "pendingEvents", "[", "$", "...
Flush all pending events for the given connection. @param \Illuminate\Database\ConnectionInterface $connection @return void
[ "Flush", "all", "pending", "events", "for", "the", "given", "connection", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L161-L175
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.rollback
public function rollback(ConnectionInterface $connection) { $connectionId = $connection->getName(); if ($this->transactionLevel > 1) { array_pop($this->pendingEvents[$connectionId][$this->transactionLevel]); } else { unset($this->pendingEvents[$connectionId]); } $this->transactionLevel--; }
php
public function rollback(ConnectionInterface $connection) { $connectionId = $connection->getName(); if ($this->transactionLevel > 1) { array_pop($this->pendingEvents[$connectionId][$this->transactionLevel]); } else { unset($this->pendingEvents[$connectionId]); } $this->transactionLevel--; }
[ "public", "function", "rollback", "(", "ConnectionInterface", "$", "connection", ")", "{", "$", "connectionId", "=", "$", "connection", "->", "getName", "(", ")", ";", "if", "(", "$", "this", "->", "transactionLevel", ">", "1", ")", "{", "array_pop", "(", ...
Clear enqueued events. @param \Illuminate\Database\ConnectionInterface $connection @return void
[ "Clear", "enqueued", "events", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L183-L194
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.isTransactionalEvent
private function isTransactionalEvent(ConnectionInterface $connection, $event) { if ($this->isPrepared($connection) && $this->transactionLevel > 0) { return $this->shouldHandle($event); } return false; }
php
private function isTransactionalEvent(ConnectionInterface $connection, $event) { if ($this->isPrepared($connection) && $this->transactionLevel > 0) { return $this->shouldHandle($event); } return false; }
[ "private", "function", "isTransactionalEvent", "(", "ConnectionInterface", "$", "connection", ",", "$", "event", ")", "{", "if", "(", "$", "this", "->", "isPrepared", "(", "$", "connection", ")", "&&", "$", "this", "->", "transactionLevel", ">", "0", ")", ...
Check whether an event is a transactional event or not. @param \Illuminate\Database\ConnectionInterface $connection @param string|object $event @return bool
[ "Check", "whether", "an", "event", "is", "a", "transactional", "event", "or", "not", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L225-L232
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.shouldHandle
private function shouldHandle($event) { if ($event instanceof TransactionalEvent) { return true; } $event = is_string($event) ? $event : get_class($event); foreach ($this->excluded as $excluded) { if ($this->matches($excluded, $event)) { return false; } } foreach ($this->transactional as $transactionalEvent) { if ($this->matches($transactionalEvent, $event)) { return true; } } return false; }
php
private function shouldHandle($event) { if ($event instanceof TransactionalEvent) { return true; } $event = is_string($event) ? $event : get_class($event); foreach ($this->excluded as $excluded) { if ($this->matches($excluded, $event)) { return false; } } foreach ($this->transactional as $transactionalEvent) { if ($this->matches($transactionalEvent, $event)) { return true; } } return false; }
[ "private", "function", "shouldHandle", "(", "$", "event", ")", "{", "if", "(", "$", "event", "instanceof", "TransactionalEvent", ")", "{", "return", "true", ";", "}", "$", "event", "=", "is_string", "(", "$", "event", ")", "?", "$", "event", ":", "get_...
Check whether an event should be handled by this layer or not. @param string|object $event @return bool
[ "Check", "whether", "an", "event", "should", "be", "handled", "by", "this", "layer", "or", "not", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L240-L261
fntneves/laravel-transactional-events
src/Neves/Events/TransactionalDispatcher.php
TransactionalDispatcher.matches
private function matches($pattern, $event) { return (Str::contains($pattern, '*') && Str::is($pattern, $event)) || Str::startsWith($event, $pattern); }
php
private function matches($pattern, $event) { return (Str::contains($pattern, '*') && Str::is($pattern, $event)) || Str::startsWith($event, $pattern); }
[ "private", "function", "matches", "(", "$", "pattern", ",", "$", "event", ")", "{", "return", "(", "Str", "::", "contains", "(", "$", "pattern", ",", "'*'", ")", "&&", "Str", "::", "is", "(", "$", "pattern", ",", "$", "event", ")", ")", "||", "St...
Check whether an event name matches a pattern or not. @param string $pattern @param string $event @return bool
[ "Check", "whether", "an", "event", "name", "matches", "a", "pattern", "or", "not", "." ]
train
https://github.com/fntneves/laravel-transactional-events/blob/a4d6bd7ab22bc6dcac519e2c5d9836d4cf42e379/src/Neves/Events/TransactionalDispatcher.php#L281-L285
pressbooks/pressbooks
inc/admin/class-sitemap.php
SiteMap.adminBar
public function adminBar() { global $wp_admin_bar; if ( ! $wp_admin_bar instanceof \WP_Admin_Bar ) { return; } $nodes = $wp_admin_bar->get_nodes(); if ( ! is_iterable( $nodes ) ) { return; } // First initialize the array of child/parent pairs: $relationships = []; foreach ( $nodes as $id => $node ) { $parent = ! empty( $node->parent ) ? $node->parent : 'root'; // Child : Parent $relationships[ $id ] = $parent; } $relationships['root'] = null; $tree = $this->parseAdminBarTree( $relationships ); ob_start(); $this->printAdminBarTree( $tree[0]['children'], $nodes ); $html = ob_get_clean(); $this->adminBarForSiteMap = $html; }
php
public function adminBar() { global $wp_admin_bar; if ( ! $wp_admin_bar instanceof \WP_Admin_Bar ) { return; } $nodes = $wp_admin_bar->get_nodes(); if ( ! is_iterable( $nodes ) ) { return; } // First initialize the array of child/parent pairs: $relationships = []; foreach ( $nodes as $id => $node ) { $parent = ! empty( $node->parent ) ? $node->parent : 'root'; // Child : Parent $relationships[ $id ] = $parent; } $relationships['root'] = null; $tree = $this->parseAdminBarTree( $relationships ); ob_start(); $this->printAdminBarTree( $tree[0]['children'], $nodes ); $html = ob_get_clean(); $this->adminBarForSiteMap = $html; }
[ "public", "function", "adminBar", "(", ")", "{", "global", "$", "wp_admin_bar", ";", "if", "(", "!", "$", "wp_admin_bar", "instanceof", "\\", "WP_Admin_Bar", ")", "{", "return", ";", "}", "$", "nodes", "=", "$", "wp_admin_bar", "->", "get_nodes", "(", ")...
Create links from Admin Bar @see \WP_Admin_Bar
[ "Create", "links", "from", "Admin", "Bar" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/admin/class-sitemap.php#L87-L114
pressbooks/pressbooks
inc/admin/class-sitemap.php
SiteMap.parseAdminBarTree
private function parseAdminBarTree( $tree, $root = null ) { $return = []; foreach ( $tree as $child => $parent ) { if ( $parent === $root ) { // Remove item from tree (we don't need to traverse this again) unset( $tree[ $child ] ); // Append the child into result array and parse its children $return[] = [ 'name' => $child, 'children' => $this->parseAdminBarTree( $tree, $child ), ]; } } return empty( $return ) ? null : $return; }
php
private function parseAdminBarTree( $tree, $root = null ) { $return = []; foreach ( $tree as $child => $parent ) { if ( $parent === $root ) { // Remove item from tree (we don't need to traverse this again) unset( $tree[ $child ] ); // Append the child into result array and parse its children $return[] = [ 'name' => $child, 'children' => $this->parseAdminBarTree( $tree, $child ), ]; } } return empty( $return ) ? null : $return; }
[ "private", "function", "parseAdminBarTree", "(", "$", "tree", ",", "$", "root", "=", "null", ")", "{", "$", "return", "=", "[", "]", ";", "foreach", "(", "$", "tree", "as", "$", "child", "=>", "$", "parent", ")", "{", "if", "(", "$", "parent", "=...
Parse Admin Bar tree (recursive) Children nodes without a parent node will be dropped @see \WP_Admin_Bar @param array $tree @param mixed $root @return array|null
[ "Parse", "Admin", "Bar", "tree", "(", "recursive", ")", "Children", "nodes", "without", "a", "parent", "node", "will", "be", "dropped" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/admin/class-sitemap.php#L127-L141
pressbooks/pressbooks
inc/admin/class-sitemap.php
SiteMap.printAdminBarTree
private function printAdminBarTree( $tree, $nodes, $ul = true ) { if ( is_countable( $tree ) && count( $tree ) > 0 ) { if ( $ul ) { echo '<ul class="ul-disc">'; } foreach ( $tree as $node ) { $title = trim( strip_tags( html_entity_decode( $nodes[ $node['name'] ]->title ) ) ); $href = $nodes[ $node['name'] ]->href; if ( ! empty( $title ) && $href !== '#' ) { echo "<li><a href='{$href}'>{$title}</a>"; $this->printAdminBarTree( $node['children'], $nodes, true ); echo '</li>'; } else { $this->printAdminBarTree( $node['children'], $nodes, false ); } } if ( $ul ) { echo '</ul>'; } } }
php
private function printAdminBarTree( $tree, $nodes, $ul = true ) { if ( is_countable( $tree ) && count( $tree ) > 0 ) { if ( $ul ) { echo '<ul class="ul-disc">'; } foreach ( $tree as $node ) { $title = trim( strip_tags( html_entity_decode( $nodes[ $node['name'] ]->title ) ) ); $href = $nodes[ $node['name'] ]->href; if ( ! empty( $title ) && $href !== '#' ) { echo "<li><a href='{$href}'>{$title}</a>"; $this->printAdminBarTree( $node['children'], $nodes, true ); echo '</li>'; } else { $this->printAdminBarTree( $node['children'], $nodes, false ); } } if ( $ul ) { echo '</ul>'; } } }
[ "private", "function", "printAdminBarTree", "(", "$", "tree", ",", "$", "nodes", ",", "$", "ul", "=", "true", ")", "{", "if", "(", "is_countable", "(", "$", "tree", ")", "&&", "count", "(", "$", "tree", ")", ">", "0", ")", "{", "if", "(", "$", ...
Print Admin Bar tree (recursive) @param array $tree @param \stdClass[] $nodes @param bool $ul @see \WP_Admin_Bar
[ "Print", "Admin", "Bar", "tree", "(", "recursive", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/admin/class-sitemap.php#L153-L173
pressbooks/pressbooks
inc/admin/class-sitemap.php
SiteMap.printMenuTree
private function printMenuTree() { /* * The elements in the array are : * 0: Menu item name * 1: Minimum level or capability required. * 2: The URL of the item's file * 3: Class * 4: ID * 5: Icon for top level menu */ global $menu, $submenu; if ( ! is_iterable( $menu ) ) { return; } echo '<ul class="ul-disc">'; foreach ( $menu as $arr1 ) { if ( empty( $arr1[0] ) ) { continue; } $menu_hook = get_plugin_page_hook( $arr1[2], null ); if ( $menu_hook ) { $href = 'admin.php?page=' . $arr1[2]; } else { $href = $arr1[2]; } echo "<li><a href='{$href}'>{$arr1[0]}</a>"; foreach ( $submenu as $k => $arr2 ) { if ( $k === $arr1[2] ) { echo '<ul class="ul-disc">'; foreach ( $arr2 as $arr3 ) { $menu_hook = get_plugin_page_hook( $arr3[2], $k ); if ( $menu_hook ) { if ( str_ends_with( $k, '.php' ) ) { $href = "{$k}?page={$arr3[2]}"; } else { $href = "admin.php?page={$arr3[2]}"; } } else { $href = $arr3[2]; } echo "<li><a href='{$href}'>{$arr3[0]}</a>"; } echo '</ul>'; continue; } } } echo '</ul>'; }
php
private function printMenuTree() { /* * The elements in the array are : * 0: Menu item name * 1: Minimum level or capability required. * 2: The URL of the item's file * 3: Class * 4: ID * 5: Icon for top level menu */ global $menu, $submenu; if ( ! is_iterable( $menu ) ) { return; } echo '<ul class="ul-disc">'; foreach ( $menu as $arr1 ) { if ( empty( $arr1[0] ) ) { continue; } $menu_hook = get_plugin_page_hook( $arr1[2], null ); if ( $menu_hook ) { $href = 'admin.php?page=' . $arr1[2]; } else { $href = $arr1[2]; } echo "<li><a href='{$href}'>{$arr1[0]}</a>"; foreach ( $submenu as $k => $arr2 ) { if ( $k === $arr1[2] ) { echo '<ul class="ul-disc">'; foreach ( $arr2 as $arr3 ) { $menu_hook = get_plugin_page_hook( $arr3[2], $k ); if ( $menu_hook ) { if ( str_ends_with( $k, '.php' ) ) { $href = "{$k}?page={$arr3[2]}"; } else { $href = "admin.php?page={$arr3[2]}"; } } else { $href = $arr3[2]; } echo "<li><a href='{$href}'>{$arr3[0]}</a>"; } echo '</ul>'; continue; } } } echo '</ul>'; }
[ "private", "function", "printMenuTree", "(", ")", "{", "/*\n\t\t* The elements in the array are :\n\t\t* 0: Menu item name\n\t\t* 1: Minimum level or capability required.\n\t\t* 2: The URL of the item's file\n\t\t* 3: Class\n\t\t* 4: ID\n\t\t* 5: Icon for top level menu\n\t\t*/", "global",...
Print Menu & Submenu Tree
[ "Print", "Menu", "&", "Submenu", "Tree" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/admin/class-sitemap.php#L178-L227
pressbooks/pressbooks
inc/interactive/class-h5p.php
H5P.apiInit
public function apiInit() { try { if ( ! is_plugin_active( 'h5p/h5p.php' ) ) { \H5P_Plugin::get_instance()->rest_api_init(); } if ( get_option( 'blog_public' ) ) { add_filter( 'h5p_rest_api_all_permission', '__return_true' ); } } catch ( \Throwable $e ) { return false; } return true; }
php
public function apiInit() { try { if ( ! is_plugin_active( 'h5p/h5p.php' ) ) { \H5P_Plugin::get_instance()->rest_api_init(); } if ( get_option( 'blog_public' ) ) { add_filter( 'h5p_rest_api_all_permission', '__return_true' ); } } catch ( \Throwable $e ) { return false; } return true; }
[ "public", "function", "apiInit", "(", ")", "{", "try", "{", "if", "(", "!", "is_plugin_active", "(", "'h5p/h5p.php'", ")", ")", "{", "\\", "H5P_Plugin", "::", "get_instance", "(", ")", "->", "rest_api_init", "(", ")", ";", "}", "if", "(", "get_option", ...
Defines REST API callbacks @return bool
[ "Defines", "REST", "API", "callbacks" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-h5p.php#L69-L81
pressbooks/pressbooks
inc/interactive/class-h5p.php
H5P.fetch
public function fetch( $url ) { try { $new_h5p_id = \H5P_Plugin::get_instance()->fetch_h5p( $url ); } catch ( \Throwable $e ) { $new_h5p_id = 0; } return $new_h5p_id; }
php
public function fetch( $url ) { try { $new_h5p_id = \H5P_Plugin::get_instance()->fetch_h5p( $url ); } catch ( \Throwable $e ) { $new_h5p_id = 0; } return $new_h5p_id; }
[ "public", "function", "fetch", "(", "$", "url", ")", "{", "try", "{", "$", "new_h5p_id", "=", "\\", "H5P_Plugin", "::", "get_instance", "(", ")", "->", "fetch_h5p", "(", "$", "url", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{"...
Download and add H5P content from given url. @param string $url @return int
[ "Download", "and", "add", "H5P", "content", "from", "given", "url", "." ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-h5p.php#L90-L97
pressbooks/pressbooks
inc/interactive/class-h5p.php
H5P.replaceShortcode
public function replaceShortcode( $atts ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] global $wpdb; $h5p_url = wp_get_shortlink( $id ); $h5p_title = get_the_title( $id ); if ( empty( $h5p_title ) ) { $h5p_title = get_bloginfo( 'name' ); } if ( isset( $atts['slug'] ) ) { $suppress = $wpdb->suppress_errors(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}h5p_contents WHERE slug=%s", $atts['slug'] ), ARRAY_A ); if ( isset( $row['id'] ) ) { $atts['id'] = $row['id']; } $wpdb->suppress_errors( $suppress ); } $h5p_id = isset( $atts['id'] ) ? intval( $atts['id'] ) : 0; // H5P Content if ( $h5p_id ) { try { $content = \H5P_Plugin::get_instance()->get_content( $h5p_id ); if ( is_array( $content ) && ! empty( $content['title'] ) ) { $h5p_title = $content['title']; } } catch ( \Throwable $e ) { // Do nothing } } // HTML $html = $this->blade->render( 'interactive.shared', [ 'title' => $h5p_title, 'url' => $h5p_url, ] ); return $html; }
php
public function replaceShortcode( $atts ) { global $id; // This is the Post ID, [@see WP_Query::setup_postdata, ...] global $wpdb; $h5p_url = wp_get_shortlink( $id ); $h5p_title = get_the_title( $id ); if ( empty( $h5p_title ) ) { $h5p_title = get_bloginfo( 'name' ); } if ( isset( $atts['slug'] ) ) { $suppress = $wpdb->suppress_errors(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}h5p_contents WHERE slug=%s", $atts['slug'] ), ARRAY_A ); if ( isset( $row['id'] ) ) { $atts['id'] = $row['id']; } $wpdb->suppress_errors( $suppress ); } $h5p_id = isset( $atts['id'] ) ? intval( $atts['id'] ) : 0; // H5P Content if ( $h5p_id ) { try { $content = \H5P_Plugin::get_instance()->get_content( $h5p_id ); if ( is_array( $content ) && ! empty( $content['title'] ) ) { $h5p_title = $content['title']; } } catch ( \Throwable $e ) { // Do nothing } } // HTML $html = $this->blade->render( 'interactive.shared', [ 'title' => $h5p_title, 'url' => $h5p_url, ] ); return $html; }
[ "public", "function", "replaceShortcode", "(", "$", "atts", ")", "{", "global", "$", "id", ";", "// This is the Post ID, [@see WP_Query::setup_postdata, ...]", "global", "$", "wpdb", ";", "$", "h5p_url", "=", "wp_get_shortlink", "(", "$", "id", ")", ";", "$", "h...
Replace [h5p] shortcode with standard text (used in exports) @see \H5P_Plugin::shortcode @param array $atts @return string
[ "Replace", "[", "h5p", "]", "shortcode", "with", "standard", "text", "(", "used", "in", "exports", ")" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-h5p.php#L117-L163
pressbooks/pressbooks
inc/interactive/class-h5p.php
H5P.replaceUncloneable
public function replaceUncloneable( $content, $ids = [] ) { $pattern = get_shortcode_regex( [ self::SHORTCODE ] ); $callback = function ( $shortcode ) use ( $ids ) { $warning = __( 'The original version of this chapter contained H5P content. You may want to remove or replace this element.', 'pressbooks' ); if ( empty( $ids ) ) { return $warning; } else { $shortcode_attrs = shortcode_parse_atts( $shortcode[3] ); if ( is_array( $shortcode_attrs ) && isset( $shortcode_attrs['id'] ) ) { // Remove quotes, return just the integer $my_id = $shortcode_attrs['id']; $my_id = trim( $my_id, "'" ); $my_id = trim( $my_id, '"' ); $my_id = str_replace( '&quot;', '', $my_id ); if ( in_array( $my_id, (array) $ids, false ) ) { // @codingStandardsIgnoreLine return $warning; } } } return $shortcode[0]; }; $content = preg_replace_callback( "/$pattern/", $callback, $content ); return $content; }
php
public function replaceUncloneable( $content, $ids = [] ) { $pattern = get_shortcode_regex( [ self::SHORTCODE ] ); $callback = function ( $shortcode ) use ( $ids ) { $warning = __( 'The original version of this chapter contained H5P content. You may want to remove or replace this element.', 'pressbooks' ); if ( empty( $ids ) ) { return $warning; } else { $shortcode_attrs = shortcode_parse_atts( $shortcode[3] ); if ( is_array( $shortcode_attrs ) && isset( $shortcode_attrs['id'] ) ) { // Remove quotes, return just the integer $my_id = $shortcode_attrs['id']; $my_id = trim( $my_id, "'" ); $my_id = trim( $my_id, '"' ); $my_id = str_replace( '&quot;', '', $my_id ); if ( in_array( $my_id, (array) $ids, false ) ) { // @codingStandardsIgnoreLine return $warning; } } } return $shortcode[0]; }; $content = preg_replace_callback( "/$pattern/", $callback, $content ); return $content; }
[ "public", "function", "replaceUncloneable", "(", "$", "content", ",", "$", "ids", "=", "[", "]", ")", "{", "$", "pattern", "=", "get_shortcode_regex", "(", "[", "self", "::", "SHORTCODE", "]", ")", ";", "$", "callback", "=", "function", "(", "$", "shor...
Replace imported/cloned [h5p] shortcodes with warning @param string $content @param int[]|int $ids (optional) @return string
[ "Replace", "imported", "/", "cloned", "[", "h5p", "]", "shortcodes", "with", "warning" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-h5p.php#L173-L200
pressbooks/pressbooks
inc/interactive/class-h5p.php
H5P.findAllShortcodeIds
public function findAllShortcodeIds( $content ) { $ids = []; $matches = []; $regex = get_shortcode_regex( [ self::SHORTCODE ] ); if ( preg_match_all( '/' . $regex . '/s', $content, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $shortcode ) { $shortcode_attrs = shortcode_parse_atts( $shortcode[3] ); if ( is_array( $shortcode_attrs ) && isset( $shortcode_attrs['id'] ) ) { // Remove quotes, return just the integer $my_id = $shortcode_attrs['id']; $my_id = trim( $my_id, "'" ); $my_id = trim( $my_id, '"' ); $my_id = str_replace( '&quot;', '', $my_id ); $ids[] = (int) $my_id; } } } return $ids; }
php
public function findAllShortcodeIds( $content ) { $ids = []; $matches = []; $regex = get_shortcode_regex( [ self::SHORTCODE ] ); if ( preg_match_all( '/' . $regex . '/s', $content, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $shortcode ) { $shortcode_attrs = shortcode_parse_atts( $shortcode[3] ); if ( is_array( $shortcode_attrs ) && isset( $shortcode_attrs['id'] ) ) { // Remove quotes, return just the integer $my_id = $shortcode_attrs['id']; $my_id = trim( $my_id, "'" ); $my_id = trim( $my_id, '"' ); $my_id = str_replace( '&quot;', '', $my_id ); $ids[] = (int) $my_id; } } } return $ids; }
[ "public", "function", "findAllShortcodeIds", "(", "$", "content", ")", "{", "$", "ids", "=", "[", "]", ";", "$", "matches", "=", "[", "]", ";", "$", "regex", "=", "get_shortcode_regex", "(", "[", "self", "::", "SHORTCODE", "]", ")", ";", "if", "(", ...
@param string $content @return int[]
[ "@param", "string", "$content" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/interactive/class-h5p.php#L207-L225
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.getChapterParent
protected function getChapterParent() { $q = new \WP_Query(); $args = [ 'post_type' => 'part', 'post_status' => [ 'draft', 'web-only', 'private', 'publish' ], 'posts_per_page' => 1, 'orderby' => 'menu_order', 'order' => 'ASC', 'no_found_rows' => true, 'cache_results' => false, 'update_post_meta_cache' => false, 'update_post_term_cache ' => false, ]; $results = $q->query( $args ); return absint( $results[0]->ID ); }
php
protected function getChapterParent() { $q = new \WP_Query(); $args = [ 'post_type' => 'part', 'post_status' => [ 'draft', 'web-only', 'private', 'publish' ], 'posts_per_page' => 1, 'orderby' => 'menu_order', 'order' => 'ASC', 'no_found_rows' => true, 'cache_results' => false, 'update_post_meta_cache' => false, 'update_post_term_cache ' => false, ]; $results = $q->query( $args ); return absint( $results[0]->ID ); }
[ "protected", "function", "getChapterParent", "(", ")", "{", "$", "q", "=", "new", "\\", "WP_Query", "(", ")", ";", "$", "args", "=", "[", "'post_type'", "=>", "'part'", ",", "'post_status'", "=>", "[", "'draft'", ",", "'web-only'", ",", "'private'", ",",...
Get a valid Part id to act as post_parent to a Chapter @return int
[ "Get", "a", "valid", "Part", "id", "to", "act", "as", "post_parent", "to", "a", "Chapter" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L120-L139
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.flaggedForImport
protected function flaggedForImport( $id ) { $chapters = getset( '_POST', 'chapters' ); if ( ! is_array( $chapters ) ) { return false; } if ( ! isset( $chapters[ $id ] ) ) { return false; } if ( ! isset( $chapters[ $id ]['import'] ) ) { return false; } return ( 1 === (int) $chapters[ $id ]['import'] ? true : false ); }
php
protected function flaggedForImport( $id ) { $chapters = getset( '_POST', 'chapters' ); if ( ! is_array( $chapters ) ) { return false; } if ( ! isset( $chapters[ $id ] ) ) { return false; } if ( ! isset( $chapters[ $id ]['import'] ) ) { return false; } return ( 1 === (int) $chapters[ $id ]['import'] ? true : false ); }
[ "protected", "function", "flaggedForImport", "(", "$", "id", ")", "{", "$", "chapters", "=", "getset", "(", "'_POST'", ",", "'chapters'", ")", ";", "if", "(", "!", "is_array", "(", "$", "chapters", ")", ")", "{", "return", "false", ";", "}", "if", "(...
Check against what the user selected for import in our form @param $id @return bool
[ "Check", "against", "what", "the", "user", "selected", "for", "import", "in", "our", "form" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L149-L166
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.determinePostType
protected function determinePostType( $id ) { $chapters = getset( '_POST', 'chapters' ); $supported_types = apply_filters( 'pb_import_custom_post_types', [ 'front-matter', 'chapter', 'part', 'back-matter', 'metadata', 'glossary' ] ); $default = 'chapter'; if ( ! is_array( $chapters ) ) { return $default; } if ( ! isset( $chapters[ $id ] ) && ! isset( $chapters[ $id ]['type'] ) ) { return $default; } if ( ! in_array( $chapters[ $id ]['type'], $supported_types, true ) ) { return $default; } return $chapters[ $id ]['type']; }
php
protected function determinePostType( $id ) { $chapters = getset( '_POST', 'chapters' ); $supported_types = apply_filters( 'pb_import_custom_post_types', [ 'front-matter', 'chapter', 'part', 'back-matter', 'metadata', 'glossary' ] ); $default = 'chapter'; if ( ! is_array( $chapters ) ) { return $default; } if ( ! isset( $chapters[ $id ] ) && ! isset( $chapters[ $id ]['type'] ) ) { return $default; } if ( ! in_array( $chapters[ $id ]['type'], $supported_types, true ) ) { return $default; } return $chapters[ $id ]['type']; }
[ "protected", "function", "determinePostType", "(", "$", "id", ")", "{", "$", "chapters", "=", "getset", "(", "'_POST'", ",", "'chapters'", ")", ";", "$", "supported_types", "=", "apply_filters", "(", "'pb_import_custom_post_types'", ",", "[", "'front-matter'", "...
Check against what the user selected for post_type in our form @param string $id @return string
[ "Check", "against", "what", "the", "user", "selected", "for", "post_type", "in", "our", "form" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L176-L195
pressbooks/pressbooks
inc/modules/import/class-import.php
Import.formSubmit
static public function formSubmit() { // -------------------------------------------------------------------------------------------------------- // Sanity check if ( false === static::isFormSubmission() || false === current_user_can( 'edit_posts' ) ) { // Don't do anything in this function, bail. return; } // -------------------------------------------------------------------------------------------------------- // Determine at what stage of the import we are and do something about it $redirect_url = get_admin_url( get_current_blog_id(), '/tools.php?page=pb_import' ); // Revoke if ( ! empty( $_GET['revoke'] ) && check_admin_referer( 'pb-revoke-import' ) ) { self::_revokeCurrentImport(); \Pressbooks\Redirect\location( $redirect_url ); } if ( isset( $_GET['import'] ) && ! empty( $_POST['import_type'] ) && check_admin_referer( 'pb-import' ) ) { self::setImportOptions(); // STEP 1 } // Default, back to form \Pressbooks\Redirect\location( $redirect_url ); }
php
static public function formSubmit() { // -------------------------------------------------------------------------------------------------------- // Sanity check if ( false === static::isFormSubmission() || false === current_user_can( 'edit_posts' ) ) { // Don't do anything in this function, bail. return; } // -------------------------------------------------------------------------------------------------------- // Determine at what stage of the import we are and do something about it $redirect_url = get_admin_url( get_current_blog_id(), '/tools.php?page=pb_import' ); // Revoke if ( ! empty( $_GET['revoke'] ) && check_admin_referer( 'pb-revoke-import' ) ) { self::_revokeCurrentImport(); \Pressbooks\Redirect\location( $redirect_url ); } if ( isset( $_GET['import'] ) && ! empty( $_POST['import_type'] ) && check_admin_referer( 'pb-import' ) ) { self::setImportOptions(); // STEP 1 } // Default, back to form \Pressbooks\Redirect\location( $redirect_url ); }
[ "static", "public", "function", "formSubmit", "(", ")", "{", "// --------------------------------------------------------------------------------------------------------", "// Sanity check", "if", "(", "false", "===", "static", "::", "isFormSubmission", "(", ")", "||", "false",...
Catch form submissions @see pressbooks/templates/admin/import.php @see \Pressbooks\EventStreams::importBook
[ "Catch", "form", "submissions" ]
train
https://github.com/pressbooks/pressbooks/blob/1a2294414a3abb7b97c5b669cee72470a8fb5806/inc/modules/import/class-import.php#L238-L265