sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getParentDirectories()
{
if ($this->isCurrentDirectoryBase()) {
return [];
}
$currentDir = $this->currentDir;
$dirs = [];
do {
$dir = dirname($currentDir);
$dirs[] = $this->getPathRelativeToBaseDir($dir)
?: DIRECTORY_SEPARATOR;
$currentDir = $dir;
} while ($dir !== $this->baseDir);
return array_reverse($dirs);
} | Returns parent directories of current directory.
@return array | entailment |
public function handle($request, Closure $next, $guard = null)
{
$locale = $this->determinerManager->determineLocale($request);
$this->app->setLocale($locale);
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string|null $guard
@return mixed | entailment |
public function add($item)
{
// init array
if (!is_array($this->_get($this->getAttributeName()))) {
$this->_set($this->getAttributeName(), []);
}
// current array
$currentArray = $this->_get($this->getAttributeName());
array_push($currentArray, $item);
$this
->_set($this->getAttributeName(), $currentArray)
->setInternArray($currentArray)
->setInternArrayIsArray(true)
->setInternArrayOffset(0);
return $this;
} | Default method adding item to array
@uses AbstractStructArrayBase::getAttributeName()
@uses AbstractStructArrayBase::__toString()
@uses AbstractStructArrayBase::_set()
@uses AbstractStructArrayBase::_get()
@uses AbstractStructArrayBase::setInternArray()
@uses AbstractStructArrayBase::setInternArrayIsArray()
@uses AbstractStructArrayBase::setInternArrayOffset()
@param mixed $item value
@return AbstractStructArrayBase | entailment |
public function offsetSet($offset, $value)
{
$this->internArray[$offset] = $value;
return $this->_set($this->getAttributeName(), $this->internArray);
} | Method setting value at offset
@param mixed $offset
@param mixed $value
@return AbstractStructArrayBase | entailment |
public function offsetUnset($offset)
{
if ($this->offsetExists($offset)) {
unset($this->internArray[$offset]);
$this->_set($this->getAttributeName(), $this->internArray);
}
return $this;
} | Method unsetting value at offset
@param mixed $offset
@return AbstractStructArrayBase | entailment |
public function initInternArray($array = [], $internCall = false)
{
if (is_array($array) && count($array) > 0) {
$this
->setInternArray($array)
->setInternArrayOffset(0)
->setInternArrayIsArray(true);
} elseif (!$internCall && property_exists($this, $this->getAttributeName())) {
$this->initInternArray($this->_get($this->getAttributeName()), true);
}
return $this;
} | Method initiating internArray
@uses AbstractStructArrayBase::setInternArray()
@uses AbstractStructArrayBase::setInternArrayOffset()
@uses AbstractStructArrayBase::setInternArrayIsArray()
@uses AbstractStructArrayBase::getAttributeName()
@uses AbstractStructArrayBase::initInternArray()
@uses AbstractStructArrayBase::__toString()
@param array $array the array to iterate trough
@param bool $internCall indicates that methods is calling itself
@return AbstractStructArrayBase | entailment |
public function handle()
{
$env = new Env(base_path('.env'));
$key = strtoupper($this->argument('key'));
$result = $env->delete($key)->get($key);
if ($result !== '' && ! is_null($result)) {
$env->rollback();
return $this->comment("No value was found for \"$key\" in the .env file, nothing was changed.");
}
return $this->comment("Successfully deleted the entry \"$key\" from your .env file.");
} | Execute the console command.
@return void | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$root = $treeBuilder->root('happyr_linkedin');
$root->children()
->scalarNode('http_client')->defaultValue('httplug.client')->info('A service id for a Httplug adapter')->end()
->scalarNode('http_message_factory')->defaultValue('httplug.message_factory')->info('A service id for a Httplug adapter')->end()
->scalarNode('app_id')->isRequired()->end()
->scalarNode('app_secret')->isRequired()->end()
->scalarNode('request_format')->cannotBeEmpty()->defaultValue('json')->end()
->scalarNode('response_format')->cannotBeEmpty()->defaultValue('array')->end()
->end();
return $treeBuilder;
} | {@inheritdoc} | entailment |
public function register()
{
$this->commands([
Commands\SetEnv::class,
Commands\GetEnv::class,
Commands\DeleteEnv::class,
Commands\ListEnv::class,
]);
} | Register the application services.
@return void | entailment |
public function hasPermissionTo($permission): bool
{
if (is_string($permission)) {
$permission = PermissionProxy::findByName($permission, $this->getDefaultGuardName());
}
if (! $this->getGuardNames()->contains($permission->guard_name)) {
throw GuardDoesNotMatch::create($permission->guard_name, $this->getGuardNames());
}
return $this->permissions->contains('id', $permission->id);
} | Determine if the user may perform the given permission.
@param string|Permission $permission
@return bool
@throws \Konekt\Acl\Exceptions\GuardDoesNotMatch | entailment |
public function getpdf($html)
{
// test if dompdf config exists in symfony app folder
$testFilePath = "/../../../../../../app/dompdf_config.inc.php";
if (file_exists(dirname(__FILE__).$testFilePath)) {
require_once(dirname(__FILE__).$testFilePath);
}
else {
require_once dirname(__FILE__).'/../DomPDF/dompdf_config.inc.php';
}
$this->pdf = new \DOMPDF();
$this->pdf->set_paper(DOMPDF_DEFAULT_PAPER_SIZE);
$this->pdf->load_html($html);
$this->pdf->render();
} | Render a pdf document
@param string $html The html to be rendered
@param string $docname The name of the document to be served | entailment |
public function determineLocale(Request $request)
{
return $this->hostMapping->flip()->get($request->getHost(), $this->fallback);
} | Determine the locale from the current host.
@param \Illuminate\Http\Request $request
@return string | entailment |
public function contactsAction($objectId, $page = 1)
{
$manuallyRemoved = 0;
$listFilters = ['manually_removed' => $manuallyRemoved];
if ('POST' === $this->request->getMethod() && $this->request->request->has('includeEvents')) {
$filters = [
'includeEvents' => InputHelper::clean($this->request->get('includeEvents', [])),
];
$this->get('session')->set('mautic.segment.filters', $filters);
} else {
$filters = [];
}
if (!empty($filters)) {
if (isset($filters['includeEvents']) && in_array('manually_added', $filters['includeEvents'])) {
$listFilters = array_merge($listFilters, ['manually_added' => 1]);
}
if (isset($filters['includeEvents']) && in_array('manually_removed', $filters['includeEvents'])) {
$listFilters = array_merge($listFilters, ['manually_removed' => 1]);
}
if (isset($filters['includeEvents']) && in_array('filter_added', $filters['includeEvents'])) {
$listFilters = array_merge($listFilters, ['manually_added' => 0]);
}
}
// get count first and pass it in. Its better this way. Trust me.
/** @var LeadListRepository $listRepo */
$listRepo = $this->container->get('mautic.lead.repository.lead_list');
$listCount = $listRepo->getLeadCount([$objectId]);
return $this->generateContactsGrid(
$objectId,
$page,
'lead:lists:viewother',
'segment',
'lead_lists_leads',
null,
'leadlist_id',
$listFilters,
null,
null,
[],
null,
'entity.lead_id',
'DESC',
$listCount[$objectId],
null,
null
);
} | @param $objectId
@param int $page
@return mixed|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response | entailment |
public function initSoapClient(array $options)
{
$wsdlOptions = [];
$defaultWsdlOptions = static::getDefaultWsdlOptions();
foreach ($defaultWsdlOptions as $optionName => $optionValue) {
if (array_key_exists($optionName, $options) && !is_null($options[$optionName])) {
$wsdlOptions[str_replace(self::OPTION_PREFIX, '', $optionName)] = $options[$optionName];
} elseif (!is_null($optionValue)) {
$wsdlOptions[str_replace(self::OPTION_PREFIX, '', $optionName)] = $optionValue;
}
}
if (self::canInstantiateSoapClientWithOptions($wsdlOptions)) {
$wsdlUrl = null;
if (array_key_exists(str_replace(self::OPTION_PREFIX, '', self::WSDL_URL), $wsdlOptions)) {
$wsdlUrl = $wsdlOptions[str_replace(self::OPTION_PREFIX, '', self::WSDL_URL)];
unset($wsdlOptions[str_replace(self::OPTION_PREFIX, '', self::WSDL_URL)]);
}
$soapClientClassName = $this->getSoapClientClassName();
$this->setSoapClient(new $soapClientClassName($wsdlUrl, $wsdlOptions));
}
} | Method initiating SoapClient
@uses ApiClassMap::classMap()
@uses AbstractSoapClientBase::getDefaultWsdlOptions()
@uses AbstractSoapClientBase::getSoapClientClassName()
@uses AbstractSoapClientBase::setSoapClient()
@uses AbstractSoapClientBase::OPTION_PREFIX
@param array $options WSDL options
@return void | entailment |
protected static function canInstantiateSoapClientWithOptions($wsdlOptions)
{
return (
array_key_exists(str_replace(self::OPTION_PREFIX, '', self::WSDL_URL), $wsdlOptions) ||
(
array_key_exists(str_replace(self::OPTION_PREFIX, '', self::WSDL_URI), $wsdlOptions) &&
array_key_exists(str_replace(self::OPTION_PREFIX, '', self::WSDL_LOCATION), $wsdlOptions)
)
);
} | Checks if the provided options are sufficient to instantiate a SoapClient:
- WSDL-mode : only the WSDL is required
- non-WSDL-mode : URI and LOCATION are required, WSDL url can be empty then
@uses AbstractSoapClientBase::OPTION_PREFIX
@param $wsdlOptions
@return bool | entailment |
public function getSoapClientClassName($soapClientClassName = null)
{
$className = self::DEFAULT_SOAP_CLIENT_CLASS;
if (!empty($soapClientClassName) && is_subclass_of($soapClientClassName, '\SoapClient')) {
$className = $soapClientClassName;
}
return $className;
} | Returns the SoapClient class name to use to create the instance of the SoapClient.
The SoapClient class is determined based on the package name.
If a class is named as {Api}SoapClient, then this is the class that will be used.
Be sure that this class inherits from the native PHP SoapClient class and this class has been loaded or can be loaded.
The goal is to allow the override of the SoapClient without having to modify this generated class.
Then the overridding SoapClient class can override for example the SoapClient::__doRequest() method if it is needed.
@uses AbstractSoapClientBase::DEFAULT_SOAP_CLIENT_CLASS
@return string | entailment |
public static function getDefaultWsdlOptions()
{
return [
self::WSDL_AUTHENTICATION => null,
self::WSDL_CACHE_WSDL => WSDL_CACHE_NONE,
self::WSDL_CLASSMAP => null,
self::WSDL_COMPRESSION => null,
self::WSDL_CONNECTION_TIMEOUT => null,
self::WSDL_ENCODING => null,
self::WSDL_EXCEPTIONS => true,
self::WSDL_FEATURES => SOAP_SINGLE_ELEMENT_ARRAYS | SOAP_USE_XSI_ARRAY_TYPE,
self::WSDL_LOCAL_CERT => null,
self::WSDL_LOCATION => null,
self::WSDL_LOGIN => null,
self::WSDL_PASSPHRASE => null,
self::WSDL_PASSWORD => null,
self::WSDL_PROXY_HOST => null,
self::WSDL_PROXY_LOGIN => null,
self::WSDL_PROXY_PASSWORD => null,
self::WSDL_PROXY_PORT => null,
self::WSDL_SOAP_VERSION => null,
self::WSDL_SSL_METHOD => null,
self::WSDL_STREAM_CONTEXT => null,
self::WSDL_STYLE => null,
self::WSDL_TRACE => true,
self::WSDL_TYPEMAP => null,
self::WSDL_URL => null,
self::WSDL_URI => null,
self::WSDL_USE => null,
self::WSDL_USER_AGENT => null,
];
} | Method returning all default options values
@uses AbstractSoapClientBase::WSDL_AUTHENTICATION
@uses AbstractSoapClientBase::WSDL_CACHE_WSDL
@uses AbstractSoapClientBase::WSDL_CLASSMAP
@uses AbstractSoapClientBase::WSDL_COMPRESSION
@uses AbstractSoapClientBase::WSDL_CONNECTION_TIMEOUT
@uses AbstractSoapClientBase::WSDL_ENCODING
@uses AbstractSoapClientBase::WSDL_EXCEPTIONS
@uses AbstractSoapClientBase::WSDL_FEATURES
@uses AbstractSoapClientBase::WSDL_LOCAL_CERT
@uses AbstractSoapClientBase::WSDL_LOCATION
@uses AbstractSoapClientBase::WSDL_LOGIN
@uses AbstractSoapClientBase::WSDL_PASSPHRASE
@uses AbstractSoapClientBase::WSDL_PASSWORD
@uses AbstractSoapClientBase::WSDL_PROXY_HOST
@uses AbstractSoapClientBase::WSDL_PROXY_LOGIN
@uses AbstractSoapClientBase::WSDL_PROXY_PASSWORD
@uses AbstractSoapClientBase::WSDL_PROXY_PORT
@uses AbstractSoapClientBase::WSDL_SOAP_VERSION
@uses AbstractSoapClientBase::WSDL_SSL_METHOD
@uses AbstractSoapClientBase::WSDL_STREAM_CONTEXT
@uses AbstractSoapClientBase::WSDL_STYLE
@uses AbstractSoapClientBase::WSDL_TRACE
@uses AbstractSoapClientBase::WSDL_TYPEMAP
@uses AbstractSoapClientBase::WSDL_URL
@uses AbstractSoapClientBase::WSDL_URI
@uses AbstractSoapClientBase::WSDL_USE
@uses AbstractSoapClientBase::WSDL_USER_AGENT
@uses WSDL_CACHE_NONE
@uses SOAP_SINGLE_ELEMENT_ARRAYS
@uses SOAP_USE_XSI_ARRAY_TYPE
@return array | entailment |
public function setLocation($location)
{
if ($this->getSoapClient() instanceof \SoapClient) {
$this->getSoapClient()->__setLocation($location);
}
return $this;
} | Allows to set the SoapClient location to call
@uses AbstractSoapClientBase::getSoapClient()
@uses SoapClient::__setLocation()
@param string $location
@return AbstractSoapClientBase | entailment |
public static function convertStringHeadersToArray($headers)
{
$lines = explode("\r\n", $headers);
$headers = [];
foreach ($lines as $line) {
if (strpos($line, ':')) {
$headerParts = explode(':', $line);
$headers[$headerParts[0]] = trim(implode(':', array_slice($headerParts, 1)));
}
}
return $headers;
} | Returns an associative array between the headers name and their respective values
@param string $headers
@return string[] | entailment |
public function setSoapHeader($nameSpace, $name, $data, $mustUnderstand = false, $actor = null)
{
if ($this->getSoapClient()) {
$defaultHeaders = (isset($this->getSoapClient()->__default_headers) && is_array($this->getSoapClient()->__default_headers)) ? $this->getSoapClient()->__default_headers : [];
foreach ($defaultHeaders as $index => $soapHeader) {
if ($soapHeader->name === $name) {
unset($defaultHeaders[$index]);
break;
}
}
$this->getSoapClient()->__setSoapheaders(null);
if (!empty($actor)) {
array_push($defaultHeaders, new \SoapHeader($nameSpace, $name, $data, $mustUnderstand, $actor));
} else {
array_push($defaultHeaders, new \SoapHeader($nameSpace, $name, $data, $mustUnderstand));
}
$this->getSoapClient()->__setSoapheaders($defaultHeaders);
}
return $this;
} | Sets a SoapHeader to send
For more information, please read the online documentation on {@link http://www.php.net/manual/en/class.soapheader.php}
@uses AbstractSoapClientBase::getSoapClient()
@uses SoapClient::__setSoapheaders()
@param string $nameSpace SoapHeader namespace
@param string $name SoapHeader name
@param mixed $data SoapHeader data
@param bool $mustUnderstand
@param string $actor
@return AbstractSoapClientBase | entailment |
public function setHttpHeader($headerName, $headerValue)
{
$state = false;
if ($this->getSoapClient() && !empty($headerName)) {
$streamContext = $this->getStreamContext();
if ($streamContext === null) {
$options = [];
$options['http'] = [];
$options['http']['header'] = '';
} else {
$options = stream_context_get_options($streamContext);
if (!array_key_exists('http', $options) || !is_array($options['http'])) {
$options['http'] = [];
$options['http']['header'] = '';
} elseif (!array_key_exists('header', $options['http'])) {
$options['http']['header'] = '';
}
}
if (count($options) && array_key_exists('http', $options) && is_array($options['http']) && array_key_exists('header', $options['http']) && is_string($options['http']['header'])) {
$lines = explode("\r\n", $options['http']['header']);
/**
* Ensure there is only one header entry for this header name
*/
$newLines = [];
foreach ($lines as $line) {
if (!empty($line) && strpos($line, $headerName) === false) {
array_push($newLines, $line);
}
}
/**
* Add new header entry
*/
array_push($newLines, "$headerName: $headerValue");
/**
* Set the context http header option
*/
$options['http']['header'] = implode("\r\n", $newLines);
/**
* Create context if it does not exist
*/
if ($streamContext === null) {
$state = ($this->getSoapClient()->_stream_context = stream_context_create($options)) ? true : false;
} else {
/**
* Set the new context http header option
*/
$state = stream_context_set_option($this->getSoapClient()->_stream_context, 'http', 'header', $options['http']['header']);
}
}
}
return $state;
} | Sets the SoapClient Stream context HTTP Header name according to its value
If a context already exists, it tries to modify it
It the context does not exist, it then creates it with the header name and its value
@uses AbstractSoapClientBase::getSoapClient()
@param string $headerName
@param mixed $headerValue
@return bool | entailment |
public function getStreamContext()
{
return ($this->getSoapClient() && isset($this->getSoapClient()->_stream_context) && is_resource($this->getSoapClient()->_stream_context)) ? $this->getSoapClient()->_stream_context : null;
} | Returns current \SoapClient::_stream_context resource or null
@return resource|null | entailment |
public function getStreamContextOptions()
{
$options = [];
$context = $this->getStreamContext();
if ($context !== null) {
$options = stream_context_get_options($context);
}
return $options;
} | Returns current \SoapClient::_stream_context resource options or empty array
@return array | entailment |
public function getLastErrorForMethod($methodName)
{
return array_key_exists($methodName, $this->lastError) ? $this->lastError[$methodName] : null;
} | Method getting the last error for a certain method
@param string $methodName method name to get error from
@return \SoapFault|null | entailment |
public function handle()
{
$env = new Env(base_path('.env'));
$key = strtoupper($this->argument('key'));
$value = (string) $this->argument('value');
$linebreak = (bool) $this->option('line-break');
$result = $env->set($key, $value, $linebreak)->get($key);
if ($result !== $value) {
$env->rollback();
return $this->error('Could not set the value in your .env file, reverting...');
}
return $this->comment("Successfully set [$key] to [$value] in your .env file.");
} | Execute the console command.
@return void | entailment |
public function handle()
{
$env = new Env(base_path('.env'));
$name = (string) $this->option('name');
try {
$env->copy(
base_path($name, Env::COPY_FOR_DISTRIBUTION)
);
return $this->comment("Successfully created the file [$name]");
} catch (\Exception $e) {
return $this->error($e->getMessage());
}
} | Execute the console command.
@return void | entailment |
public static function getFormatedXml($string, $asDomDocument = false)
{
if (!is_null($string)) {
$domDocument = self::getDOMDocument($string);
return $asDomDocument ? $domDocument : $domDocument->saveXML();
}
return null;
} | Returns a XML string content as a DOMDocument or as a formated XML string
@throws \InvalidArgumentException
@param string $string
@param bool $asDomDocument
@return \DOMDocument|string|null | entailment |
public function handle()
{
$env = new Env(base_path('.env'));
$data = [];
foreach ($env->all() as $key => $value) {
$data[] = [$key, $value];
}
return $this->table(['Key', 'Value'], $data);
} | Execute the console command.
@return void | entailment |
public function browse($base = '0', $browseflag = 'BrowseDirectChildren', $start = 0, $count = 0)
{
libxml_use_internal_errors(true); //is this still needed?
$args = array(
'ObjectID'=>$base,
'BrowseFlag'=>$browseflag,
'Filter'=>'',
'StartingIndex'=>$start,
'RequestedCount'=>$count,
'SortCriteria'=>'',
);
$response = $this->upnp->sendRequestToDevice('Browse', $args, $this->ctrlurl, $type = 'ContentDirectory');
if($response){
$doc = new \DOMDocument();
$doc->loadXML($response);
$containers = $doc->getElementsByTagName('container');
$items = $doc->getElementsByTagName('item');
$directories = array();
foreach($containers as $container){
foreach($container->attributes as $attr){
if($attr->name == 'id'){
$id = $attr->nodeValue;
}
if($attr->name === 'parentID'){
$parentId = $attr->nodeValue;
}
}
$directories[$id]['parentID'] = $parentId;
foreach($container->childNodes as $property){
foreach($property->attributes as $attr){
}
$directories[$id][$property->nodeName] = $property->nodeValue;
}
}
foreach($items as $item){
foreach($item->attributes as $attr){
if($attr->name == 'id'){
$id = $attr->nodeValue;
}
if($attr->name === 'parentID'){
$parentId = $attr->nodeValue;
}
}
$directories[$id]['parentID'] = $parentId;
foreach($item->childNodes as $property){
if($property->nodeName === 'res'){
$att_length = $property->attributes->length;
for($i = 0; $i < $att_length; ++$i){
if($property->attributes->item($i)->name === 'protocolInfo' && strpos($property->attributes->item($i)->value, 'video')){
$directories[$id]['video'] = $property->nodeValue;
}
}
}
$directories[$id][$property->nodeName] = $property->nodeValue;
}
}
return $directories;
}
return false;
} | BrowseDirectChildren or BrowseMetadata | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('ijanki_ftp');
$rootNode = method_exists($treeBuilder, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('ijanki_ftp');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
} | {@inheritDoc} | entailment |
public function putContents($file_name, $data, $mode = FTP_ASCII)
{
if (!is_resource($this->resource)) {
throw new FtpException("Not connected to FTP server. Call connect() or ssl_connect() first.");
}
$temp = tmpfile();
fwrite($temp, $data);
fseek($temp, 0);
return $this->fput($file_name, $temp, $mode);
} | Put a string in remote $file_name | entailment |
public function connectUrl($url)
{
if(!preg_match('!^ftp(?<ssl>s?)://(?<user>[^:]+):(?<pass>[^@]+)@(?<host>[^:/]+)(?:[:](?<port>\d+))?(?<path>.*)$!i', $url, $match)) {
throw new FtpException('Url must be in format: ftp[s]://username:password@hostname[:port]/[path]');
}
// default port if necessary
if (empty($match['port'])) {
$match['port'] = '21';
}
// determine and invoke connect method
$connectMethod = (bool) $match['ssl'] ? 'ssl_connect' : 'connect';
$this->$connectMethod($match['host'], $match['port']);
// authenticate
if (!$this->login($match['user'], $match['pass'])) {
throw new FtpException("Login failed as " . $match['user']);
}
// normalize and change to path, if one given
$match['path'] = trim($match['path'], '/');
if (!empty($match['path'])) {
$this->chdir("/$match[path]/");
}
} | Interpret connection info from url string | entailment |
public function generateHash(array $data)
{
if ($this->getSecretKey()) {
//begin HASH calculation
ksort($data);
$hashString = "";
foreach ($data as $key => $val) {
$hashString .= strlen($val) . $val;
}
return hash_hmac("md5", $hashString, $this->getSecretKey());
}
} | HMAC_MD5 signature applied on all parameters from the request.
Source string for HMAC_MD5 will be calculated by adding the length
of each field value at the beginning of field value. A common key
shared between PayU and the merchant is used for the signature.
Find more details on how is HASH generated https://secure.payu.com.tr/docs/alu/v3/#hash
@param array $data
@return string | entailment |
public function reset()
{
$this->values[self::PROTOCOL_VERSION] = null;
$this->values[self::SOURCE_ID] = null;
$this->values[self::DESTINATION_ID] = null;
$this->values[self::NNAMESPACE] = null;
$this->values[self::PAYLOAD_TYPE] = null;
$this->values[self::PAYLOAD_UTF8] = null;
$this->values[self::PAYLOAD_BINARY] = null;
} | Clears message values and sets default ones
@return null | entailment |
public function getChannels()
{
$response = $this->channel->addMessage('query/apps', false);
$xml = simplexml_load_string($response);
$channels = array();
foreach($xml->app as $app){
$app_id = $app->attributes()->id;
$channels[(string)$app_id] = array(
'name' => (string)$app,
'launch_url' => $this->location.'launch/'.(string)$app_id, //url to post to for launching channel
'icon_url' => $this->location.'query/icon/'.(string)$app_id, //url containing image src for channel icon
);
}
return $channels;
} | to not confuse with communication channels, consider renaming to getApplications | entailment |
public static function indentLines($lines, $indent = ' ')
{
$lineSeparator = "\n";
$buffer = '';
$line = strtok($lines, $lineSeparator);
while ($line) {
$buffer .= $indent . $line . $lineSeparator;
$line = strtok($lineSeparator);
}
strtok(null, null);
return $buffer;
} | indentLines()
this will add a line-separator at the end of the last line because if it was
empty it is not any longer and deserves one.
@param string $lines
@param string $indent (optional)
@return string | entailment |
public static function startTag($name, $attributes, $emptyTag = false)
{
$buffer = '<' . $name;
$buffer .= static::attributes($attributes);
$buffer .= $emptyTag ? '/>' : '>';
return $buffer;
} | @param string $name
@param array|Traversable $attributes attributeName => attributeValue string pairs
@param bool $emptyTag create an empty element tag (commonly known as short tags)
@return string | entailment |
public static function attributes($attributes)
{
$buffer = '';
foreach ($attributes as $name => $value) {
$buffer .= ' ' . $name . '="' . static::attributeValue($value) . '"';
}
return $buffer;
} | @param array|Traversable $attributes attributeName => attributeValue string pairs
@return string | entailment |
public static function attributeValue($value)
{
$buffer = $value;
// REC-xml/#AVNormalize - preserve
// REC-xml/#sec-line-ends - preserve
$buffer = preg_replace_callback('~\r\n|\r(?!\n)|\t~', array('self', 'numericEntitiesSingleByte'), $buffer);
return htmlspecialchars($buffer, ENT_QUOTES, 'UTF-8', false);
} | @param string $value
@see XMLBuild::numericEntitiesSingleByte
@return string | entailment |
public static function wrapTag($name, $attributes, $innerXML)
{
if (!strlen($innerXML)) {
return XMLBuild::startTag($name, $attributes, true);
}
return
XMLBuild::startTag($name, $attributes)
. "\n"
. XMLBuild::indentLines($innerXML)
. "</$name>";
} | @param string $name
@param array|Traversable $attributes attributeName => attributeValue string pairs
@param string $innerXML
@return string | entailment |
public static function readerNode(XMLReader $reader)
{
switch ($reader->nodeType) {
case XMLREADER::NONE:
return '%(0)%';
case XMLReader::ELEMENT:
return XMLBuild::startTag($reader->name, new XMLAttributeIterator($reader));
default:
$node = new XMLReaderNode($reader);
$nodeTypeName = $node->getNodeTypeName();
$nodeType = $reader->nodeType;
return sprintf('%%%s (%d)%%', $nodeTypeName, $nodeType);
}
} | @param XMLReader $reader
@return string | entailment |
private static function numericEntitiesSingleByte($matches)
{
$buffer = str_split($matches[0]);
foreach ($buffer as &$char) {
$char = sprintf('&#%d;', ord($char));
}
return implode('', $buffer);
} | @param array $matches
@return string
@see attributeValue() | entailment |
public function moveToNextByNodeType($nodeType)
{
if (null === self::valid()) {
self::rewind();
} elseif (self::valid()) {
self::next();
}
while (self::valid()) {
if ($this->reader->nodeType === $nodeType) {
break;
}
self::next();
}
return self::valid() ? self::current() : false;
} | @param int $nodeType
@return bool|\XMLReaderNode | entailment |
private function moveReaderToCurrent()
{
if (
($this->reader->nodeType === XMLReader::NONE)
or ($this->reader->nodeType !== XMLReader::ELEMENT)
or ($this->localName && $this->localName !== $this->reader->localName)
) {
self::next();
}
} | move cursor to the next element but only if it's not yet there | entailment |
public function isEndElementOfEmptyElement()
{
return
$this->reader->nodeType === XMLReader::END_ELEMENT
&& $this->lastDepth === $this->reader->depth
&& $this->lastNode instanceof DOMElement
&& !$this->reader->isEmptyElement;
} | The element by marked by type XMLReader::END_ELEMENT
is empty (has no children) but not self-closing.
@return bool | entailment |
public function getSimpleXMLElement()
{
if (null === $this->simpleXML) {
if ($this->reader->nodeType !== XMLReader::ELEMENT) {
return null;
}
$node = $this->expand();
$this->simpleXML = simplexml_import_dom($node);
}
return $this->simpleXML;
} | SimpleXMLElement for XMLReader::ELEMENT
@return SimpleXMLElement|null in case the current node can not be converted into a SimpleXMLElement
@since 0.1.4 | entailment |
public function getAttribute($name, $default = null)
{
$value = $this->reader->getAttribute($name);
return null !== $value ? $value : $default;
} | @param string $name attribute name
@param string $default (optional) if the attribute with $name does not exists, the value to return
@return null|string value of the attribute, if attribute with $name does not exists null (by $default) | entailment |
public function getChildElements($name = null, $descendantAxis = false)
{
return new XMLChildElementIterator($this->reader, $name, $descendantAxis);
} | @param string $name (optional) element name, null or '*' stand for each element
@param bool $descendantAxis descend into children of children and so on?
@return XMLChildElementIterator|XMLReaderNode[] | entailment |
public function readOuterXml()
{
// Compatibility libxml 20620 (2.6.20) or later - LIBXML_VERSION / LIBXML_DOTTED_VERSION
if (method_exists($this->reader, 'readOuterXml')) {
return $this->reader->readOuterXml();
}
if (0 === $this->reader->nodeType) {
return '';
}
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$node = $this->expand($doc);
return $doc->saveXML($node);
} | Decorated method
@throws BadMethodCallException in case XMLReader can not expand the node
@return string | entailment |
public function expand(DOMNode $basenode = null)
{
if (null === $basenode) {
$basenode = new DomDocument();
}
if ($basenode instanceof DOMDocument) {
$doc = $basenode;
} else {
$doc = $basenode->ownerDocument;
}
if (false === $node = $this->reader->expand($basenode)) {
throw new BadMethodCallException('Unable to expand node.');
}
if ($node->ownerDocument !== $doc) {
$node = $doc->importNode($node, true);
}
return $node;
} | XMLReader expand node and import it into a DOMNode with a DOMDocument
This is for example useful for DOMDocument::saveXML() @see readOuterXml
or getting a SimpleXMLElement out of it @see getSimpleXMLElement
@throws BadMethodCallException
@param DOMNode $basenode
@return DOMNode | entailment |
public function readString()
{
// Compatibility libxml 20620 (2.6.20) or later - LIBXML_VERSION / LIBXML_DOTTED_VERSION
if (method_exists($this->reader, 'readString')) {
return $this->reader->readString();
}
if (0 === $this->reader->nodeType) {
return '';
}
if (false === $node = $this->reader->expand()) {
throw new BadMethodCallException('Unable to expand node.');
}
return $node->textContent;
} | Decorated method
@throws BadMethodCallException
@return string | entailment |
public function getNodeTypeName($nodeType = null)
{
$strings = array(
XMLReader::NONE => 'NONE',
XMLReader::ELEMENT => 'ELEMENT',
XMLReader::ATTRIBUTE => 'ATTRIBUTE',
XMLREADER::TEXT => 'TEXT',
XMLREADER::CDATA => 'CDATA',
XMLReader::ENTITY_REF => 'ENTITY_REF',
XMLReader::ENTITY => 'ENTITY',
XMLReader::PI => 'PI',
XMLReader::COMMENT => 'COMMENT',
XMLReader::DOC => 'DOC',
XMLReader::DOC_TYPE => 'DOC_TYPE',
XMLReader::DOC_FRAGMENT => 'DOC_FRAGMENT',
XMLReader::NOTATION => 'NOTATION',
XMLReader::WHITESPACE => 'WHITESPACE',
XMLReader::SIGNIFICANT_WHITESPACE => 'SIGNIFICANT_WHITESPACE',
XMLReader::END_ELEMENT => 'END_ELEMENT',
XMLReader::END_ENTITY => 'END_ENTITY',
XMLReader::XML_DECLARATION => 'XML_DECLARATION',
);
if (null === $nodeType) {
$nodeType = $this->nodeType;
}
return $strings[$nodeType];
} | Return node-type as human readable string (constant name)
@param null $nodeType
@return string | entailment |
public static function dump(XMLReader $reader, $return = FALSE)
{
$node = new self($reader);
$nodeType = $reader->nodeType;
$nodeName = $node->getNodeTypeName();
$extra = '';
if ($reader->nodeType === XMLReader::ELEMENT) {
$extra = '<' . $reader->name . '> ';
$extra .= sprintf("(isEmptyElement: %s) ", $reader->isEmptyElement ? 'Yes' : 'No');
}
if ($reader->nodeType === XMLReader::END_ELEMENT) {
$extra = '</' . $reader->name . '> ';
}
if ($reader->nodeType === XMLReader::ATTRIBUTE) {
$str = $reader->value;
$len = strlen($str);
if ($len > 20) {
$str = substr($str, 0, 17) . '...';
}
$str = strtr($str, array("\n" => '\n'));
$extra = sprintf('%s = (%d) "%s" ', $reader->name, strlen($str), $str);
}
if ($reader->nodeType === XMLReader::TEXT || $reader->nodeType === XMLReader::WHITESPACE || $reader->nodeType === XMLReader::SIGNIFICANT_WHITESPACE) {
$str = $reader->readString();
$len = strlen($str);
if ($len > 20) {
$str = substr($str, 0, 17) . '...';
}
$str = strtr($str, array("\n" => '\n'));
$extra = sprintf('(%d) "%s" ', strlen($str), $str);
}
$label = sprintf("(#%d) %s %s", $nodeType, $nodeName, $extra);
if ($return) {
return $label;
}
printf("%s%s\n", str_repeat(' ', $reader->depth), $label);
return null;
} | debug utility method
@param XMLReader $reader
@param bool $return (optional) prints by default but can return string
@return string|null | entailment |
private function ensureCurrentElementState()
{
if ($this->reader->nodeType !== XMLReader::ELEMENT) {
$this->moveToNextElementByName($this->name);
} elseif ($this->name && $this->name !== $this->reader->name) {
$this->moveToNextElementByName($this->name);
}
} | take care the underlying XMLReader is at an element with a fitting name (if $this is looking for a name) | entailment |
public function fopen($filename, $mode, $use_include_path = null, $context = null) {
if ($mode !== self::MODE_READ_BINARY) {
$message = sprintf(
"unsupported mode '%s', only '%s' is supported for buffered file read", $mode, self::MODE_READ_BINARY
);
trigger_error($message);
return false;
}
if ($context === null) {
$handle = fopen($filename, self::MODE_READ_BINARY, $use_include_path);
} else {
$handle = fopen($filename, self::MODE_READ_BINARY, $use_include_path, $context);
}
if (!$handle) {
return false;
}
$this->file = $filename;
$this->handle = $handle;
return true;
} | @param $filename
@param $mode
@param null $use_include_path
@param null $context
@return bool | entailment |
public function append($count)
{
$bufferLen = strlen($this->buffer);
if ($bufferLen >= $count + $this->maxAhead) {
return $bufferLen;
}
($ahead = $this->readAhead)
&& ($delta = $bufferLen - $ahead) < 0
&& $count -= $delta;
$read = fread($this->handle, $count);
if ($read === false) {
throw new UnexpectedValueException(sprintf('Can not deal with fread() errors.'));
}
if ($readLen = strlen($read)) {
$this->buffer .= $read;
$bufferLen += $readLen;
}
return $bufferLen;
} | appends up to $count bytes to the buffer up to
the read-ahead limit
@param $count
@return int|bool length of buffer or FALSE on error | entailment |
public function shift($bytes)
{
$bufferLen = strlen($this->buffer);
if ($bytes === $bufferLen) {
$return = $this->buffer;
$this->buffer = '';
} else {
$return = substr($this->buffer, 0, $bytes);
$this->buffer = substr($this->buffer, $bytes);
}
return $return;
} | shift bytes from buffer
@param $bytes - up to buffer-length bytes
@return string | entailment |
public function getReaderForFile($filename, $mode, $use_include_path, $context)
{
$readers = $this->readers;
if (!isset($readers[$filename])) {
$reader = new BufferedFileRead();
$result = $reader->fopen($filename, $mode, $use_include_path, $context);
return $this->readers[$filename] = $result ? $reader : null;
}
return $readers[$filename];
} | @param $filename
@param $mode
@param $use_include_path
@param $context
@return BufferedFileRead or null on error | entailment |
public static function closeBuffer($path)
{
if (!self::$readers) {
return false;
}
$path = new XMLSequenceStreamPath($path);
$file = $path->getFile();
return self::$readers->removeReaderForFile($file);
} | @param string $path filename of the buffer to close, complete with wrapper prefix
@return bool | entailment |
public static function notAtEndOfSequence($path)
{
if (!self::$readers) {
return true;
}
try {
$path = new XMLSequenceStreamPath($path);
} catch (UnexpectedValueException $e) {
return true;
}
$file = $path->getFile();
return !self::$readers->isFileConsumed($file);
} | @param $path
@return bool | entailment |
public function stream_open($path, $mode, $options, &$opened_path)
{
# fputs(STDOUT, sprintf('<open: %s - raise errors: %d - use path: %d >', var_export($path, 1), $options & STREAM_REPORT_ERRORS, $options & STREAM_USE_PATH));
$path = new XMLSequenceStreamPath($path);
$file = $path->getFile();
$reader = self::$readers->getReaderForFile($file, $mode, null, $this->context);
$this->file = $file;
$this->reader = $reader;
if (!$reader) {
return false;
}
$reader->setReadAhead(256);
if ($reader->feof() && !strlen($reader->buffer)) {
$message = sprintf('Concatenated XML Stream: Resource %s at the end of stream', var_export($file, true));
trigger_error($message);
return false;
}
return true;
} | @param string $path
@param string $mode
@param int $options
@param string $opened_path
@return bool | entailment |
public function getControlURL($description_url, $service = 'AVTransport')
{
$description = $this->getDescription($description_url);
switch($service)
{
case 'AVTransport':
$serviceType = 'urn:schemas-upnp-org:service:AVTransport:1';
break;
default:
$serviceType = 'urn:schemas-upnp-org:service:AVTransport:1';
break;
}
foreach($description['device']['serviceList']['service'] as $service)
{
if($service['serviceType'] == $serviceType)
{
$url = parse_url($description_url);
return $url['scheme'].'://'.$url['host'].':'.$url['port'].$service['controlURL'];
}
}
} | this should be moved to the upnp and renderer model | entailment |
public function daysInMonth($year, $month)
{
if ($year <= 0) {
throw new InvalidArgumentException('Year ' . $year . ' is invalid for this calendar');
} elseif ($month < 1 || $month > 13) {
throw new InvalidArgumentException('Month ' . $month . ' is invalid for this calendar');
} elseif ($month !== 13) {
return 30;
} elseif ($this->isLeapYear($year)) {
return 6;
} else {
return 5;
}
} | Determine the number of days in a specified month, allowing for leap years, etc.
@param int $year
@param int $month
@return int | entailment |
public function jdToYmd($julian_day)
{
$depoch = $julian_day - 2121446; // 1 Farvardīn 475
$cycle = (int) floor($depoch / 1029983);
$cyear = $this->mod($depoch, 1029983);
if ($cyear == 1029982) {
$ycycle = 2820;
} else {
$aux1 = (int) ($cyear / 366);
$aux2 = $cyear % 366;
$ycycle = (int) (((2134 * $aux1) + (2816 * $aux2) + 2815) / 1028522) + $aux1 + 1;
}
$year = $ycycle + (2820 * $cycle) + 474;
// If we allowed negative years, we would deal with them here.
$yday = $julian_day - $this->ymdToJd($year, 1, 1) + 1;
$month = ($yday <= 186) ? ceil($yday / 31) : ceil(($yday - 6) / 30);
$day = $julian_day - $this->ymdToJd($year, $month, 1) + 1;
return array((int) $year, (int) $month, (int) $day);
} | Convert a Julian day number into a year/month/day.
@param int $julian_day
@return int[] | entailment |
public function ymdToJd($year, $month, $day)
{
if ($month < 1 || $month > $this->monthsInYear()) {
throw new InvalidArgumentException('Month ' . $month . ' is invalid for this calendar');
}
$epbase = $year - (($year >= 0) ? 474 : 473);
$epyear = 474 + $this->mod($epbase, 2820);
return
$day +
(($month <= 7) ? (($month - 1) * 31) : ((($month - 1) * 30) + 6)) +
(int) ((($epyear * 682) - 110) / 2816) +
($epyear - 1) * 365 +
(int) (floor($epbase / 2820)) * 1029983 +
$this->jdStart() - 1;
} | Convert a year/month/day to a Julian day number.
@param int $year
@param int $month
@param int $day
@return int | entailment |
public function mod($dividend, $divisor)
{
if ($divisor === 0) {
return 0;
}
$modulus = $dividend % $divisor;
if ($modulus < 0) {
$modulus += $divisor;
}
return $modulus;
} | The PHP modulus function returns a negative modulus for a negative dividend.
This algorithm requires a "traditional" modulus function where the modulus is
always positive.
@param int $dividend
@param int $divisor
@return int | entailment |
public function save(Identifiable $data)
{
Assertion::isInstanceOf($data, $this->class);
$serializedReadModel = $this->serializer->serialize($data);
$params = [
'index' => $this->index,
'type' => $serializedReadModel['class'],
'id' => $data->getId(),
'body' => $serializedReadModel['payload'],
'refresh' => true,
];
$this->client->index($params);
} | {@inheritDoc} | entailment |
public function find($id)
{
$params = [
'index' => $this->index,
'type' => $this->class,
'id' => $id,
];
try {
$result = $this->client->get($params);
} catch (Missing404Exception $e) {
return null;
}
return $this->deserializeHit($result);
} | {@inheritDoc} | entailment |
public function remove($id)
{
try {
$this->client->delete([
'id' => $id,
'index' => $this->index,
'type' => $this->class,
'refresh' => true,
]);
} catch (Missing404Exception $e) { // It was already deleted or never existed, fine by us!
}
} | {@inheritDoc} | entailment |
public function createIndex(): bool
{
$class = $this->class;
$indexParams = [
'index' => $this->index,
];
if (count($this->notAnalyzedFields)) {
$indexParams['body'] = [
'mappings' => [
$class => [
'_source' => [
'enabled' => true
],
'properties' => $this->createNotAnalyzedFieldsMapping($this->notAnalyzedFields),
]
]
];
}
$this->client->indices()->create($indexParams);
$response = $this->client->cluster()->health([
'index' => $this->index,
'wait_for_status' => 'yellow',
'timeout' => '5s',
]);
return isset($response['status']) && $response['status'] !== 'red';
} | Creates the index for this repository's ReadModel.
@return boolean True, if the index was successfully created | entailment |
public function deleteIndex(): bool
{
$indexParams = [
'index' => $this->index,
'timeout' => '5s',
];
$this->client->indices()->delete($indexParams);
$response = $this->client->cluster()->health([
'index' => $this->index,
'wait_for_status' => 'yellow',
'timeout' => '5s',
]);
return isset($response['status']) && $response['status'] !== 'red';
} | Deletes the index for this repository's ReadModel.
@return True, if the index was successfully deleted | entailment |
public function ymdToJd($year, $month, $day)
{
if ($month < 1 || $month > $this->monthsInYear()) {
throw new InvalidArgumentException('Month ' . $month . ' is invalid for this calendar');
}
if ($year < 0) {
// 1 BCE is 0, 2 BCE is -1, etc.
++$year;
}
$a = (int) ((14 - $month) / 12);
$year = $year + 4800 - $a;
$month = $month + 12 * $a - 3;
return $day + (int) ((153 * $month + 2) / 5) + 365 * $year + (int) ($year / 4) - (int) ($year / 100) + (int) ($year / 400) - 32045;
} | Convert a year/month/day into a Julian day number
@param int $year
@param int $month
@param int $day
@return int | entailment |
public function easterDays($year)
{
// The “golden” number
$golden = $year % 19 + 1;
// The “dominical” number (finding a Sunday)
$dom = ($year + (int) ($year / 4) - (int) ($year / 100) + (int) ($year / 400)) % 7;
if ($dom < 0) {
$dom += 7;
}
// The solar correction
$solar = (int) (($year - 1600) / 100) - (int) (($year - 1600) / 400);
// The lunar correction
$lunar = (int) ((int) (($year - 1400) / 100) * 8) / 25;
// The uncorrected “Paschal full moon” date
$pfm = (3 - 11 * $golden + $solar - $lunar) % 30;
if ($pfm < 0) {
$pfm += 30;
}
// The corrected “Paschal full moon” date
if ($pfm === 29 || $pfm === 28 && $golden > 11) {
$pfm--;
}
$tmp = (4 - $pfm - $dom) % 7;
if ($tmp < 0) {
$tmp += 7;
}
return $pfm + $tmp + 1;
} | Get the number of days after March 21 that easter falls, for a given year.
Uses the algorithm found in PHP’s ext/calendar/easter.c
@param int $year
@return int | entailment |
public static function create()
{
self::$french_calendar = new FrenchCalendar();
self::$gregorian_calendar = new GregorianCalendar();
self::$jewish_calendar = new JewishCalendar(array(
JewishCalendar::EMULATE_BUG_54254 => self::shouldEmulateBug54254(),
));
self::$julian_calendar = new JulianCalendar();
} | Create the necessary shims to emulate the ext/calendar package.
@return void | entailment |
public static function calDaysInMonth($calendar_id, $month, $year)
{
switch ($calendar_id) {
case CAL_FRENCH:
return self::calDaysInMonthFrench($year, $month);
case CAL_GREGORIAN:
return self::calDaysInMonthCalendar(self::$gregorian_calendar, $year, $month);
case CAL_JEWISH:
return self::calDaysInMonthCalendar(self::$jewish_calendar, $year, $month);
case CAL_JULIAN:
return self::calDaysInMonthCalendar(self::$julian_calendar, $year, $month);
default:
return trigger_error('invalid calendar ID ' . $calendar_id, E_USER_WARNING);
}
} | Return the number of days in a month for a given year and calendar.
Shim implementation of cal_days_in_month()
@link https://php.net/cal_days_in_month
@link https://bugs.php.net/bug.php?id=67976
@param int $calendar_id
@param int $month
@param int $year
@return int|bool The number of days in the specified month, or false on error | entailment |
private static function calDaysInMonthCalendar(CalendarInterface $calendar, $year, $month)
{
try {
return $calendar->daysInMonth($year, $month);
} catch (InvalidArgumentException $ex) {
$error_msg = PHP_VERSION_ID < 70200 ? 'invalid date.' : 'invalid date';
return trigger_error($error_msg, E_USER_WARNING);
}
} | Calculate the number of days in a month in a specified (Gregorian or Julian) calendar.
@param CalendarInterface $calendar
@param int $year
@param int $month
@return int|bool | entailment |
private static function calDaysInMonthFrench($year, $month)
{
if ($month == 13 && $year == 14 && self::shouldEmulateBug67976()) {
return -2380948;
} elseif ($year > 14) {
$error_msg = PHP_VERSION_ID < 70200 ? 'invalid date.' : 'invalid date';
return trigger_error($error_msg, E_USER_WARNING);
} else {
return self::calDaysInMonthCalendar(self::$french_calendar, $year, $month);
}
} | Calculate the number of days in a month in the French calendar.
Mimic PHP’s validation of the parameters
@param int $year
@param int $month
@return int|bool | entailment |
public static function calFromJd($julian_day, $calendar_id)
{
switch ($calendar_id) {
case CAL_FRENCH:
return self::calFromJdCalendar($julian_day, self::jdToFrench($julian_day), self::$MONTH_NAMES_FRENCH, self::$MONTH_NAMES_FRENCH);
case CAL_GREGORIAN:
return self::calFromJdCalendar($julian_day, self::jdToGregorian($julian_day), self::$MONTH_NAMES, self::$MONTH_NAMES_SHORT);
case CAL_JEWISH:
$months = self::jdMonthNameJewishMonths($julian_day);
$cal = self::calFromJdCalendar($julian_day, self::jdToCalendar(self::$jewish_calendar, $julian_day, 347998, 324542846), $months, $months);
if (($julian_day < 347998 || $julian_day > 324542846) && !self::shouldEmulateBug67976()) {
$cal['dow'] = null;
$cal['dayname'] = '';
$cal['abbrevdayname'] = '';
}
return $cal;
case CAL_JULIAN:
return self::calFromJdCalendar($julian_day, self::jdToJulian($julian_day), self::$MONTH_NAMES, self::$MONTH_NAMES_SHORT);
default:
return trigger_error('invalid calendar ID ' . $calendar_id, E_USER_WARNING);
}
} | Converts from Julian Day Count to a supported calendar.
Shim implementation of cal_from_jd()
@link https://php.net/cal_from_jd
@param int $julian_day Julian Day number
@param int $calendar_id Calendar constant
@return array|bool | entailment |
private static function calFromJdCalendar($julian_day, $mdy, $months, $months_short)
{
list($month, $day, $year) = explode('/', $mdy);
return array(
'date' => $month . '/' . $day . '/' . $year,
'month' => (int) $month,
'day' => (int) $day,
'year' => (int) $year,
'dow' => self::jdDayOfWeek($julian_day, 0),
'abbrevdayname' => self::jdDayOfWeek($julian_day, 2),
'dayname' => self::jdDayOfWeek($julian_day, 1),
'abbrevmonth' => $months_short[$month],
'monthname' => $months[$month],
);
} | Convert a Julian day number to a calendar and provide details.
@param int $julian_day
@param string $mdy
@param string[] $months
@param string[] $months_short
@return array | entailment |
public static function calInfo($calendar_id)
{
switch ($calendar_id) {
case CAL_FRENCH:
return self::calInfoCalendar(self::$MONTH_NAMES_FRENCH, self::$MONTH_NAMES_FRENCH, 30, 'French', 'CAL_FRENCH');
case CAL_GREGORIAN:
return self::calInfoCalendar(self::$MONTH_NAMES, self::$MONTH_NAMES_SHORT, 31, 'Gregorian', 'CAL_GREGORIAN');
case CAL_JEWISH:
$months = self::shouldEmulateBug54254() ? self::$MONTH_NAMES_JEWISH_54254 : self::$MONTH_NAMES_JEWISH_LEAP_YEAR;
return self::calInfoCalendar($months, $months, 30, 'Jewish', 'CAL_JEWISH');
case CAL_JULIAN:
return self::calInfoCalendar(self::$MONTH_NAMES, self::$MONTH_NAMES_SHORT, 31, 'Julian', 'CAL_JULIAN');
case -1:
return array(
CAL_GREGORIAN => self::calInfo(CAL_GREGORIAN),
CAL_JULIAN => self::calInfo(CAL_JULIAN),
CAL_JEWISH => self::calInfo(CAL_JEWISH),
CAL_FRENCH => self::calInfo(CAL_FRENCH),
);
default:
return trigger_error('invalid calendar ID ' . $calendar_id, E_USER_WARNING);
}
} | Returns information about a particular calendar.
Shim implementation of cal_info()
@link https://php.net/cal_info
@param int $calendar_id
@return array|bool | entailment |
private static function calInfoCalendar($month_names, $month_names_short, $max_days_in_month, $calendar_name, $calendar_symbol)
{
return array(
'months' => array_slice($month_names, 1, null, true),
'abbrevmonths' => array_slice($month_names_short, 1, null, true),
'maxdaysinmonth' => $max_days_in_month,
'calname' => $calendar_name,
'calsymbol' => $calendar_symbol,
);
} | Returns information about the French calendar.
@param string[] $month_names
@param string[] $month_names_short
@param int $max_days_in_month
@param string $calendar_name
@param string $calendar_symbol
@return array | entailment |
public static function calToJd($calendar_id, $month, $day, $year)
{
switch ($calendar_id) {
case CAL_FRENCH:
return self::frenchToJd($month, $day, $year);
case CAL_GREGORIAN:
return self::gregorianToJd($month, $day, $year);
case CAL_JEWISH:
return self::jewishToJd($month, $day, $year);
case CAL_JULIAN:
return self::julianToJd($month, $day, $year);
default:
return trigger_error('invalid calendar ID ' . $calendar_id . '.', E_USER_WARNING);
}
} | Converts from a supported calendar to Julian Day Count
Shim implementation of cal_to_jd()
@link https://php.net/cal_to_jd
@param int $calendar_id
@param int $month
@param int $day
@param int $year
@return int|bool | entailment |
public static function easterDate($year)
{
if ($year < 1970 || $year > 2037) {
return trigger_error('This function is only valid for years between 1970 and 2037 inclusive', E_USER_WARNING);
}
$days = self::$gregorian_calendar->easterDays($year);
// Calculate time-zone offset
$date_time = new \DateTime('now', new \DateTimeZone(date_default_timezone_get()));
$offset_seconds = (int) $date_time->format('Z');
if ($days < 11) {
return self::jdtounix(self::$gregorian_calendar->ymdToJd($year, 3, $days + 21)) - $offset_seconds;
} else {
return self::jdtounix(self::$gregorian_calendar->ymdToJd($year, 4, $days - 10)) - $offset_seconds;
}
} | Get Unix timestamp for midnight on Easter of a given year.
Shim implementation of easter_date()
@link https://php.net/easter_date
@param int $year
@return int|bool | entailment |
public static function easterDays($year, $method)
{
if ($method == CAL_EASTER_ALWAYS_JULIAN ||
$method == CAL_EASTER_ROMAN && $year <= 1582 ||
$year <= 1752 && $method != CAL_EASTER_ROMAN && $method != CAL_EASTER_ALWAYS_GREGORIAN
) {
return self::$julian_calendar->easterDays($year);
} else {
return self::$gregorian_calendar->easterDays($year);
}
} | Get number of days after March 21 on which Easter falls for a given year.
Shim implementation of easter_days()
@link https://php.net/easter_days
@param int $year
@param int $method Use the Julian or Gregorian calendar
@return int | entailment |
public static function frenchToJd($month, $day, $year)
{
if ($year <= 0) {
return 0;
} else {
return self::$french_calendar->ymdToJd($year, $month, $day);
}
} | Converts a date from the French Republican Calendar to a Julian Day Count.
Shim implementation of FrenchToJD()
@link https://php.net/FrenchToJD
@param int $month
@param int $day
@param int $year
@return int | entailment |
public static function gregorianToJd($month, $day, $year)
{
if ($year == 0) {
return 0;
} else {
return self::$gregorian_calendar->ymdToJd($year, $month, $day);
}
} | Converts a Gregorian date to Julian Day Count.
Shim implementation of GregorianToJD()
@link https://php.net/GregorianToJD
@param int $month
@param int $day
@param int $year
@return int | entailment |
public static function jdDayOfWeek($julian_day, $mode)
{
$day_of_week = ($julian_day + 1) % 7;
if ($day_of_week < 0) {
$day_of_week += 7;
}
switch ($mode) {
case 1: // 1, not CAL_DOW_LONG - see bug 67960
return self::$DAY_NAMES[$day_of_week];
case 2: // 2, not CAL_DOW_SHORT - see bug 67960
return self::$DAY_NAMES_SHORT[$day_of_week];
default: // CAL_DOW_DAYNO or anything else
return $day_of_week;
}
} | Returns the day of the week.
Shim implementation of JDDayOfWeek()
@link https://php.net/JDDayOfWeek
@link https://bugs.php.net/bug.php?id=67960
@param int $julian_day
@param int $mode
@return int|string | entailment |
public static function jdMonthName($julian_day, $mode)
{
switch ($mode) {
case CAL_MONTH_GREGORIAN_LONG:
return self::jdMonthNameCalendar(self::$gregorian_calendar, $julian_day, self::$MONTH_NAMES);
case CAL_MONTH_JULIAN_LONG:
return self::jdMonthNameCalendar(self::$julian_calendar, $julian_day, self::$MONTH_NAMES);
case CAL_MONTH_JULIAN_SHORT:
return self::jdMonthNameCalendar(self::$julian_calendar, $julian_day, self::$MONTH_NAMES_SHORT);
case CAL_MONTH_JEWISH:
return self::jdMonthNameCalendar(self::$jewish_calendar, $julian_day, self::jdMonthNameJewishMonths($julian_day));
case CAL_MONTH_FRENCH:
return self::jdMonthNameCalendar(self::$french_calendar, $julian_day, self::$MONTH_NAMES_FRENCH);
case CAL_MONTH_GREGORIAN_SHORT:
default:
return self::jdMonthNameCalendar(self::$gregorian_calendar, $julian_day, self::$MONTH_NAMES_SHORT);
}
} | Returns a month name.
Shim implementation of JDMonthName()
@link https://php.net/JDMonthName
@param int $julian_day
@param int $mode
@return string | entailment |
private static function jdMonthNameCalendar(CalendarInterface $calendar, $julian_day, $months)
{
list(, $month) = $calendar->jdToYmd($julian_day);
return $months[$month];
} | Calculate the month-name for a given julian day, in a given calendar,
with given set of month names.
@param CalendarInterface $calendar
@param int $julian_day
@param string[] $months
@return string | entailment |
private static function jdMonthNameJewishMonths($julian_day)
{
list(, , $year) = explode('/', self::jdToCalendar(self::$jewish_calendar, $julian_day, 347998, 324542846));
if (self::$jewish_calendar->isLeapYear($year)) {
return self::shouldEmulateBug54254() ? self::$MONTH_NAMES_JEWISH_54254 : self::$MONTH_NAMES_JEWISH_LEAP_YEAR;
} else {
return self::shouldEmulateBug54254() ? self::$MONTH_NAMES_JEWISH_54254 : self::$MONTH_NAMES_JEWISH;
}
} | Determine which month names to use for the Jewish calendar.
@param int $julian_day
@return string[] | entailment |
private static function jdToCalendar(CalendarInterface $calendar, $julian_day, $min_jd, $max_jd)
{
if ($julian_day >= $min_jd && $julian_day <= $max_jd) {
list($year, $month, $day) = $calendar->jdToYmd($julian_day);
return $month . '/' . $day . '/' . $year;
} else {
return '0/0/0';
}
} | Convert a Julian day in a specific calendar to a day/month/year.
Julian days outside the specified range are returned as “0/0/0”.
@param CalendarInterface $calendar
@param int $julian_day
@param int $min_jd
@param int $max_jd
@return string | entailment |
public static function jdToGregorian($julian_day)
{
// PHP has different limits on 32 and 64 bit systems.
$MAX_JD = PHP_INT_SIZE == 4 ? 536838866 : 2305843009213661906;
return self::jdToCalendar(self::$gregorian_calendar, $julian_day, 1, $MAX_JD);
} | Converts Julian Day Count to Gregorian date.
Shim implementation of JDToGregorian()
@link https://php.net/JDToGregorian
@param int $julian_day A Julian Day number
@return string A string of the form "month/day/year" | entailment |
public static function jdToJewish($julian_day, $hebrew, $fl)
{
if ($hebrew) {
if ($julian_day < 347998 || $julian_day > 4000075) {
$error_msg = PHP_VERSION_ID < 70200 ? 'Year out of range (0-9999).' : 'Year out of range (0-9999)';
return trigger_error($error_msg, E_USER_WARNING);
}
return self::$jewish_calendar->jdToHebrew(
$julian_day,
(bool)($fl & CAL_JEWISH_ADD_ALAFIM_GERESH),
(bool)($fl & CAL_JEWISH_ADD_ALAFIM),
(bool)($fl & CAL_JEWISH_ADD_GERESHAYIM)
);
} else {
// The upper limit is hard-coded into PHP to prevent numeric overflow on 32 bit systems.
return self::jdToCalendar(self::$jewish_calendar, $julian_day, 347998, 324542846);
}
} | Converts a Julian day count to a Jewish calendar date.
Shim implementation of JdtoJjewish()
@link https://php.net/JdtoJewish
@param int $julian_day A Julian Day number
@param bool $hebrew If true, the date is returned in Hebrew text
@param int $fl If $hebrew is true, then add alafim and gereshayim to the text
@return string|bool A string of the form "month/day/year", or false on error | entailment |
public static function jdToJulian($julian_day)
{
// PHP has different limits on 32 and 64 bit systems.
$MAX_JD = PHP_INT_SIZE == 4 ? 536838829 : 784368370349;
return self::jdToCalendar(self::$julian_calendar, $julian_day, 1, $MAX_JD);
} | Converts a Julian Day Count to a Julian Calendar Date.
Shim implementation of JDToJulian()
@link https://php.net/JDToJulian
@param int $julian_day A Julian Day number
@return string A string of the form "month/day/year" | entailment |
public static function jewishToJd($month, $day, $year)
{
if ($year <= 0) {
return 0;
} else {
return self::$jewish_calendar->ymdToJd($year, $month, $day);
}
} | Converts a date in the Jewish Calendar to Julian Day Count.
Shim implementation of JewishToJD()
@link https://php.net/JewishToJD
@param int $month
@param int $day
@param int $year
@return int | entailment |
public static function julianToJd($month, $day, $year)
{
if ($year == 0) {
return 0;
} else {
return self::$julian_calendar->ymdToJd($year, $month, $day);
}
} | Converts a Julian Calendar date to Julian Day Count.
Shim implementation of JdToJulian()
@link https://php.net/JdToJulian
@param int $month
@param int $day
@param int $year
@return int | entailment |
public static function unixToJd($timestamp)
{
if ($timestamp < 0) {
return false;
} else {
// Convert timestamp based on local timezone
return self::GregorianToJd(gmdate('n', $timestamp), gmdate('j', $timestamp), gmdate('Y', $timestamp));
}
} | Convert Unix timestamp to Julian Day.
Shim implementation of unixtojd()
@link https://php.net/unixtojd
@param int $timestamp
@return false|int | entailment |
public function jdToYmd($julian_day)
{
$year = (int) ((30 * ($julian_day - 1948440) + 10646) / 10631);
$month = (int) ((11 * ($julian_day - $year * 354 - (int) ((3 + 11 * $year) / 30) - 1948086) + 330) / 325);
$day = $julian_day - 29 * ($month - 1) - (int) ((6 * $month - 1) / 11) - $year * 354 - (int) ((3 + 11 * $year) / 30) - 1948085;
return array($year, $month, $day);
} | Convert a Julian day number into a year/month/day.
@param int $julian_day
@return int[] | entailment |
public function ymdToJd($year, $month, $day)
{
if ($month < 1 || $month > $this->monthsInYear()) {
throw new InvalidArgumentException('Month ' . $month . ' is invalid for this calendar');
}
return $day + 29 * ($month - 1) + (int) ((6 * $month - 1) / 11) + $year * 354 + (int) ((3 + 11 * $year) / 30) + 1948085;
} | Convert a year/month/day to a Julian day number.
@param int $year
@param int $month
@param int $day
@return int | entailment |
public function create(string $name, string $class, array $notAnalyzedFields = []): Repository
{
return new ElasticSearchRepository($this->client, $this->serializer, $name, $class, $notAnalyzedFields);
} | {@inheritDoc} | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.