_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q10500
ConnectionFactory.build
train
public static function build(string $connectionName = null) : Connection { $configs = Application::current()->config('database'); $connectionName = $connectionName ?: $configs['default']; if (!isset($configs[$connectionName])) { throw new \Exception("Unknown database connection: '$connectionName'"); } if (!isset(self::$connections[$connectionName])) { $connectionClass = $configs[$connectionName]['driver']; $options = $configs[$connectionName]['options']; self::$connections[$connectionName] = new $connectionClass($options); } return self::$connections[$connectionName]; }
php
{ "resource": "" }
q10501
Http.call
train
public function call($url, $callback, $additionalData = null, $options = []) { $curlJob = $this->factory->createCurlJob($url, $callback, $additionalData, $options); // Start job execution. $this->factory->startJob($curlJob); }
php
{ "resource": "" }
q10502
Http.get
train
public function get($url, callable $callback, $additionalData = null, $options = []) { $defaultOptions = [ CURLOPT_FOLLOWLOCATION => true, CURLOPT_USERAGENT => "eXpansionPluginPack v ".AbstractApplication::EXPANSION_VERSION, ]; $options = $options + $defaultOptions; $additionalData['callback'] = $callback; $this->call($url, [$this, 'process'], $additionalData, $options); }
php
{ "resource": "" }
q10503
Http.post
train
public function post($url, $fields, callable $callback, $additionalData = null, $options = []) { $this->doCall("POST", $url, $fields, $callback, $additionalData, $options); }
php
{ "resource": "" }
q10504
Http.process
train
public function process(HttpRequest $curl) { $data = $curl->getData(); $additionalData = $curl->getAdditionalData(); $callback = $additionalData['callback']; unset($additionalData['callback']); $obj = new HttpResult($data['response'], $data['curlInfo'], $curl->getCurlError(), $additionalData); call_user_func($callback, $obj); }
php
{ "resource": "" }
q10505
LoggerException.addContext
train
public function addContext(array $context) { if ($context) { $this->context = array_merge($this->context, $context); } return $this; }
php
{ "resource": "" }
q10506
JwtController.newTokenAction
train
public function newTokenAction(Request $request, $userClass) { try { $this->get('bengor_user.' . $userClass . '.api_command_bus')->handle( new LogInUserCommand( $request->getUser(), $request->getPassword() ) ); } catch (UserDoesNotExistException $exception) { return new JsonResponse('', 400); } catch (UserEmailInvalidException $exception) { return new JsonResponse('', 400); } catch (UserInactiveException $exception) { return new JsonResponse('Inactive user', 400); } catch (UserPasswordInvalidException $exception) { return new JsonResponse('', 400); } $token = $this->get('lexik_jwt_authentication.encoder.default')->encode(['email' => $request->getUser()]); return new JsonResponse(['token' => $token]); }
php
{ "resource": "" }
q10507
ElasticaFormatter.getDocument
train
protected function getDocument($record) { $document = new Document(); $document->setData($record); $document->setType($this->type); $document->setIndex($this->index); return $document; }
php
{ "resource": "" }
q10508
CheckoutStepController.init
train
public function init() { // If the step is not a registered step exit if (!in_array($this->step, CheckoutSteps::getSteps())) { $this->redirect($this->Link('/')); } // If no ReservationSession exists redirect back to the base event controller elseif (empty(ReservationSession::get())) { $this->redirect($this->Link('/')); } // If the reservation has been processed end the session and redirect elseif (ReservationSession::get()->Status === 'PAID' && $this->step != 'success') { ReservationSession::end(); $this->redirect($this->Link('/')); } else { $this->reservation = ReservationSession::get(); parent::init(); } }
php
{ "resource": "" }
q10509
CheckoutStepController.Link
train
public function Link($action = null) { if (!$action) { $action = $this->step; } return $this->dataRecord->RelativeLink($action); }
php
{ "resource": "" }
q10510
DateUtil.Validate
train
public static function Validate($date, $format = DATEFORMAT::YMD, $separator = "/") { $timestamp = DateUtil::TimeStampFromStr($date, $format); $dateCheck = DateUtil::FormatDate($timestamp, $format, $separator, true); $date = $date . substr('--/--/---- 00:00:00', strlen($date)); $timestamp2 = DateUtil::TimeStampFromStr($dateCheck, $format); return ($timestamp == $timestamp2) && ($date == $dateCheck); }
php
{ "resource": "" }
q10511
ScriptsRenderer.get
train
public function get( $withScript = false ) { $retVal = ''; if ( $withScript ) { $retVal .= "<script type='text/javascript'>\n"; } $retVal .= $this->current(); if ( $withScript ) { $retVal .= "\n</script>\n"; } return $retVal; }
php
{ "resource": "" }
q10512
UserOptionSetField.getValue
train
public function getValue() { if ($option = $this->Options()->byID($this->getField('Value'))) { return $option->Title; } return null; }
php
{ "resource": "" }
q10513
ConvertPrice.setPrice
train
public function setPrice($price, $format = self::EURO) { $this->validatePriceFormat($format); // sanitize: price is null if value like -1.123E-11 provided if (preg_match('/^\-?\d+\.\d+E(\+|\-)\d+$/u', (string) $price)) { $this->price = 0; return $this; } if ($format == self::EURO) { // remove: all not allowed chars $price = preg_replace('/[^0-9,\-\.\+]/', '', $price); // sanitize: +/- at end of number $price = preg_replace('/^(.*)(\-|\+)$/', '$2$1', $price); // sanitize: , in price if (mb_strpos($price, ',') !== false) { if (preg_match('/,\./', $price)) { $price = str_replace(',', '', $price); } else { $price = str_replace('.', '', $price); $price = str_replace(',', '.', $price); } } // convert: to internal int structure $price = (float) $price; $price = $price * 100; } else { $price = (float) $price; } $this->price = (int) round($price); return $this; }
php
{ "resource": "" }
q10514
ConvertPrice.sanitize
train
public function sanitize($price, $format = self::EURO) { return $this->setPrice($price, $format)->getPrice($format); }
php
{ "resource": "" }
q10515
Map.initMxmaps
train
public function initMxmaps($overrideExisting = true) { if (null !== $this->collMxmaps && !$overrideExisting) { return; } $collectionClassName = MxmapTableMap::getTableMap()->getCollectionClassName(); $this->collMxmaps = new $collectionClassName; $this->collMxmaps->setModel('\eXpansion\Bundle\Maps\Model\Mxmap'); }
php
{ "resource": "" }
q10516
Map.getMxmaps
train
public function getMxmaps(Criteria $criteria = null, ConnectionInterface $con = null) { $partial = $this->collMxmapsPartial && !$this->isNew(); if (null === $this->collMxmaps || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collMxmaps) { // return empty collection $this->initMxmaps(); } else { $collMxmaps = ChildMxmapQuery::create(null, $criteria) ->filterByMap($this) ->find($con); if (null !== $criteria) { if (false !== $this->collMxmapsPartial && count($collMxmaps)) { $this->initMxmaps(false); foreach ($collMxmaps as $obj) { if (false == $this->collMxmaps->contains($obj)) { $this->collMxmaps->append($obj); } } $this->collMxmapsPartial = true; } return $collMxmaps; } if ($partial && $this->collMxmaps) { foreach ($this->collMxmaps as $obj) { if ($obj->isNew()) { $collMxmaps[] = $obj; } } } $this->collMxmaps = $collMxmaps; $this->collMxmapsPartial = false; } } return $this->collMxmaps; }
php
{ "resource": "" }
q10517
Map.countMxmaps
train
public function countMxmaps(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) { $partial = $this->collMxmapsPartial && !$this->isNew(); if (null === $this->collMxmaps || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collMxmaps) { return 0; } if ($partial && !$criteria) { return count($this->getMxmaps()); } $query = ChildMxmapQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query ->filterByMap($this) ->count($con); } return count($this->collMxmaps); }
php
{ "resource": "" }
q10518
Map.addMxmap
train
public function addMxmap(ChildMxmap $l) { if ($this->collMxmaps === null) { $this->initMxmaps(); $this->collMxmapsPartial = true; } if (!$this->collMxmaps->contains($l)) { $this->doAddMxmap($l); if ($this->mxmapsScheduledForDeletion and $this->mxmapsScheduledForDeletion->contains($l)) { $this->mxmapsScheduledForDeletion->remove($this->mxmapsScheduledForDeletion->search($l)); } } return $this; }
php
{ "resource": "" }
q10519
Services_Webservice.createServer
train
private function createServer() { $server = new SoapServer(null, $this->soapServerOptions); $server->SetClass($this->wsdlclassname); $server->handle(); }
php
{ "resource": "" }
q10520
Services_Webservice.intoStruct
train
protected function intoStruct() { $class = new ReflectionObject($this); $this->classname = $class->getName(); $this->wsdlclassname = str_replace('\\', '.', $class->getName()); $this->classMethodsIntoStruct(); $this->classStructDispatch(); }
php
{ "resource": "" }
q10521
Services_Webservice.classPropertiesIntoStruct
train
protected function classPropertiesIntoStruct($className) { if (!isset($this->wsdlStruct[$className])) { $class = new ReflectionClass($className); $properties = $class->getProperties(); $this->wsdlStruct['class'][$className]['property'] = array(); for ($i = 0; $i < count($properties); ++$i) { if ($properties[$i]->isPublic()) { preg_match_all( '~@var\s(\S+)~', $properties[$i]->getDocComment(), $var ); $_cleanType = str_replace('[]', '', $var[1][0], $_length); $_typens = str_repeat('ArrayOf', $_length); $this->wsdlStruct['class'][$className]['property'][$properties[$i]->getName()]['type'] = $_cleanType; $this->wsdlStruct['class'][$className]['property'][$properties[$i]->getName()]['wsdltype'] = $_typens.$_cleanType; $this->wsdlStruct['class'][$className]['property'][$properties[$i]->getName()]['length'] = $_length; $this->wsdlStruct['class'][$className]['property'][$properties[$i]->getName()]['array'] = ($_length > 0 && in_array($_cleanType, $this->simpleTypes)) ? true : false; $isObject = (!in_array($_cleanType, $this->simpleTypes) && new ReflectionClass($_cleanType)) ? true : false; $this->wsdlStruct['class'][$className]['property'][$properties[$i]->getName()]['class'] = $isObject; if ($isObject == true) { $this->classPropertiesIntoStruct($_cleanType); } if ($_length > 0) { $_typensSource = ''; for ($j = $_length; $j > 0; --$j) { $_typensSource .= 'ArrayOf'; $this->wsdlStruct['array'][$_typensSource.$_cleanType] = substr( $_typensSource, 0, strlen($_typensSource) - 7 ) . $_cleanType; } } } } } }
php
{ "resource": "" }
q10522
Services_Webservice.createWSDL_definitions
train
protected function createWSDL_definitions() { /* <definitions name="myService" targetNamespace="urn:myService" xmlns:typens="urn:myService" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"> */ $this->wsdl_definitions = $this->wsdl->createElement('definitions'); $this->wsdl_definitions->setAttribute('name', $this->wsdlclassname); $this->wsdl_definitions->setAttribute( 'targetNamespace', 'urn:' . $this->wsdlclassname ); $this->wsdl_definitions->setAttribute( 'xmlns:typens', 'urn:' . $this->wsdlclassname ); $this->wsdl_definitions->setAttribute( 'xmlns:xsd', self::SOAP_XML_SCHEMA_VERSION ); $this->wsdl_definitions->setAttribute( 'xmlns:soap', self::SCHEMA_SOAP ); $this->wsdl_definitions->setAttribute( 'xmlns:soapenc', self::SOAP_SCHEMA_ENCODING ); $this->wsdl_definitions->setAttribute( 'xmlns:wsdl', self::SCHEMA_WSDL ); $this->wsdl_definitions->setAttribute( 'xmlns', self::SCHEMA_WSDL ); $this->wsdl->appendChild($this->wsdl_definitions); }
php
{ "resource": "" }
q10523
Services_Webservice.createWSDL_types
train
protected function createWSDL_types() { /* <types> <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:myService"/> </types> */ $types = $this->wsdl->createElement('types'); $schema = $this->wsdl->createElement('xsd:schema'); $schema->setAttribute('xmlns', self::SOAP_XML_SCHEMA_VERSION); $schema->setAttribute('targetNamespace', 'urn:'.$this->wsdlclassname); $types->appendChild($schema); // array /* <xsd:complexType name="ArrayOfclassC"> <xsd:complexContent> <xsd:restriction base="soapenc:Array"> <xsd:attribute ref="soapenc:arrayType" wsdl:arrayType="typens:classC[]"/> </xsd:restriction> </xsd:complexContent> </xsd:complexType> */ if (isset($this->wsdlStruct['array'])) { foreach ($this->wsdlStruct['array'] as $source => $target) { //<s:complexType name="ArrayOfArrayOfInt"> //<s:sequence> //<s:element minOccurs="0" maxOccurs="unbounded" name="ArrayOfInt" nillable="true" type="tns:ArrayOfInt"/> //</s:sequence> $complexType = $this->wsdl->createElement('xsd:complexType'); $complexContent = $this->wsdl->createElement('xsd:complexContent'); $restriction = $this->wsdl->createElement('xsd:restriction'); $attribute = $this->wsdl->createElement('xsd:attribute'); $restriction->appendChild($attribute); $complexContent->appendChild($restriction); $complexType->appendChild($complexContent); $schema->appendChild($complexType); $complexType->setAttribute('name', $source); $restriction->setAttribute('base', 'soapenc:Array'); $attribute->setAttribute('ref', 'soapenc:arrayType'); try { $class = new ReflectionClass($target); } catch (Exception $e) { } if (in_array($target, $this->simpleTypes)) { $attribute->setAttribute( 'wsdl:arrayType', 'xsd:'.$target.'[]' ); } elseif (isset($class)) { $attribute->setAttribute( 'wsdl:arrayType', 'typens:'.$target.'[]' ); } else { $attribute->setAttribute( 'wsdl:arrayType', 'typens:'.$target.'[]' ); } unset($class); } } // class /* <xsd:complexType name="classB"> <xsd:all> <xsd:element name="classCArray" type="typens:ArrayOfclassC" /> </xsd:all> </xsd:complexType> */ if (isset($this->wsdlStruct['class'])) { foreach ($this->wsdlStruct['class'] as $className=>$classProperty) { $complextype = $this->wsdl->createElement('xsd:complexType'); $complextype->setAttribute('name', $className); $sequence = $this->wsdl->createElement('xsd:all'); $complextype->appendChild($sequence); $schema->appendChild($complextype); foreach ($classProperty['property'] as $cpname => $cpValue) { $element = $this->wsdl->createElement('xsd:element'); $element->setAttribute('name', $cpname); $element->setAttribute( 'type', ( in_array( $cpValue['wsdltype'], $this->simpleTypes ) ? 'xsd:' : 'typens:') . $cpValue['wsdltype'] ); $sequence->appendChild($element); } } } $this->wsdl_definitions->appendChild($types); }
php
{ "resource": "" }
q10524
Services_Webservice.createWSDL_messages
train
protected function createWSDL_messages() { /* <message name="hello"> <part name="i" type="xsd:int"/> <part name="j" type="xsd:string"/> </message> <message name="helloResponse"> <part name="helloResponse" type="xsd:string"/> </message> */ foreach ($this->wsdlStruct[$this->wsdlclassname]['method'] as $name => $method) { $messageInput = $this->wsdl->createElement('message'); $messageInput->setAttribute('name', $name); $messageOutput = $this->wsdl->createElement('message'); $messageOutput->setAttribute('name', $name . 'Response'); $this->wsdl_definitions->appendChild($messageInput); $this->wsdl_definitions->appendChild($messageOutput); foreach ($method['var'] as $methodVars) { if (isset($methodVars['param'])) { $part = $this->wsdl->createElement('part'); $part->setAttribute('name', $methodVars['name']); $part->setAttribute( 'type', (($methodVars['array'] != 1 && $methodVars['class'] != 1) ? 'xsd:' : 'typens:') . $methodVars['wsdltype'] ); $messageInput->appendChild($part); } if (isset($methodVars['return'])) { $part = $this->wsdl->createElement('part'); $part->setAttribute('name', $name.'Response'); $part->setAttribute( 'type', (($methodVars['array'] != 1 && $methodVars['class'] != 1) ? 'xsd:' : 'typens:') . $methodVars['wsdltype'] ); $messageOutput->appendChild($part); } } } }
php
{ "resource": "" }
q10525
Services_Webservice.createWSDL_binding
train
protected function createWSDL_binding() { /* <binding name="myServiceBinding" type="typens:myServicePort"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="hello"> <soap:operation soapAction="urn:myServiceAction"/> <input> <soap:body use="encoded" namespace="urn:myService" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="urn:myService" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation> </binding> */ $binding = $this->wsdl->createElement('binding'); $binding->setAttribute('name', $this->wsdlclassname . 'Binding'); $binding->setAttribute('type', 'typens:' . $this->wsdlclassname . 'Port'); $soap_binding = $this->wsdl->createElement('soap:binding'); $soap_binding->setAttribute('style', 'rpc'); $soap_binding->setAttribute('transport', self::SCHEMA_SOAP_HTTP); $binding->appendChild($soap_binding); foreach ($this->wsdlStruct[$this->wsdlclassname]['method'] as $name => $vars) { $operation = $this->wsdl->createElement('operation'); $operation->setAttribute('name', $name); $binding->appendChild($operation); $soap_operation = $this->wsdl->createElement('soap:operation'); $soap_operation->setAttribute( 'soapAction', 'urn:'.$this->wsdlclassname.'Action' ); $operation->appendChild($soap_operation); $input = $this->wsdl->createElement('input'); $output = $this->wsdl->createElement('output'); $operation->appendChild($input); $operation->appendChild($output); $soap_body = $this->wsdl->createElement('soap:body'); $soap_body->setAttribute('use', 'encoded'); $soap_body->setAttribute('namespace', 'urn:'.$this->namespace); $soap_body->setAttribute('encodingStyle', self::SOAP_SCHEMA_ENCODING); $input->appendChild($soap_body); $soap_body = $this->wsdl->createElement('soap:body'); $soap_body->setAttribute('use', 'encoded'); $soap_body->setAttribute('namespace', 'urn:'.$this->namespace); $soap_body->setAttribute('encodingStyle', self::SOAP_SCHEMA_ENCODING); $output->appendChild($soap_body); } $this->wsdl_definitions->appendChild($binding); }
php
{ "resource": "" }
q10526
Services_Webservice.createWSDL_portType
train
protected function createWSDL_portType() { /* <portType name="myServicePort"> <operation name="hello"> <input message="typens:hello"/> <output message="typens:helloResponse"/> </operation> </portType> */ $portType = $this->wsdl->createElement('portType'); $portType->setAttribute('name', $this->wsdlclassname.'Port'); foreach ($this->wsdlStruct[$this->wsdlclassname]['method'] as $methodName => $methodVars) { $operation = $this->wsdl->createElement('operation'); $operation->setAttribute('name', $methodName); $portType->appendChild($operation); $documentation = $this->wsdl->createElement('documentation'); $documentation->appendChild( $this->wsdl->createTextNode($methodVars['description']) ); $operation->appendChild($documentation); $input = $this->wsdl->createElement('input'); $output = $this->wsdl->createElement('output'); $input->setAttribute('message', 'typens:' . $methodName); $output->setAttribute('message', 'typens:' . $methodName . 'Response'); $operation->appendChild($input); $operation->appendChild($output); } $this->wsdl_definitions->appendChild($portType); }
php
{ "resource": "" }
q10527
Services_Webservice.createWSDL_service
train
protected function createWSDL_service() { /* <service name="myService"> <port name="myServicePort" binding="typens:myServiceBinding"> <soap:address location="http://dschini.org/test1.php"/> </port> </service> */ $service = $this->wsdl->createElement('service'); $service->setAttribute('name', $this->wsdlclassname); $port = $this->wsdl->createElement('port'); $port->setAttribute('name', $this->wsdlclassname . 'Port'); $port->setAttribute('binding', 'typens:' . $this->wsdlclassname . 'Binding'); $adress = $this->wsdl->createElement('soap:address'); $adress->setAttribute( 'location', $this->protocol . '://' . $_SERVER['HTTP_HOST'] . $this->getSelfUrl() ); $port->appendChild($adress); $service->appendChild($port); $this->wsdl_definitions->appendChild($service); }
php
{ "resource": "" }
q10528
AbstractServiceProvider.registerTokenParser
train
protected function registerTokenParser() { $this->app->singleton('tymon.jwt.parser', function ($app) { $parser = new Parser( $app['request'], [ new AuthHeaders, new QueryString, new InputSource, new RouteParams, new Cookies, ] ); $app->refresh('request', $parser, 'setRequest'); return $parser; }); }
php
{ "resource": "" }
q10529
Dropdown.setSelectedByValue
train
public function setSelectedByValue($value) { $x = 0; foreach ($this->options as $idx => $data) { if ($value == $data) { $this->setSelectedIndex($x); return; } $x++; } $this->setSelectedIndex(-1); }
php
{ "resource": "" }
q10530
ExamplePaymentSlipPdf.writePaymentSlipLines
train
protected function writePaymentSlipLines($elementName, $element) { echo sprintf('Write the element "%s"<br>', $elementName); parent::writePaymentSlipLines($elementName, $element); echo '<br>'; return $this; }
php
{ "resource": "" }
q10531
CostCenterManager.getCostCenterChildrenIds
train
public function getCostCenterChildrenIds($id) { $ids = array(); $this->CostCenter->byParent($id)->each(function($CostCenter) use (&$ids) { if($CostCenter->is_group) { $ids = array_merge($ids, $this->getCostCenterChildrenIds($CostCenter->id)); } array_push($ids, $CostCenter->id); }); return $ids; }
php
{ "resource": "" }
q10532
CostCenterManager.getCostCenterChildren
train
public function getCostCenterChildren($input) { $CostCenter = $this->CostCenter->byId($input['id']); $costCenterTree = array('text' => $CostCenter->key . ' ' . $CostCenter->name, 'state' => array('opened' => true), 'icon' => 'fa fa-sitemap', 'children' => array()); $this->CostCenter->byParent($input['id'])->each(function($CostCenter) use (&$costCenterTree) { if($CostCenter->is_group) { array_push($costCenterTree['children'], array('text' => $CostCenter->key . ' ' . $CostCenter->name, 'icon' => 'fa fa-sitemap')); } else { array_push($costCenterTree['children'], array('text' => $CostCenter->key . ' ' . $CostCenter->name, 'icon' => 'fa fa-leaf')); } }); return json_encode(array($costCenterTree)); }
php
{ "resource": "" }
q10533
Filter._getModelInfoFromField
train
protected function _getModelInfoFromField($field = null, $plugin = null) { $result = false; if (empty($field) || !is_string($field)) { return $result; } if (strpos($field, '.') === false) { return $result; } list($modelName, $fieldName) = pluginSplit($field); if (!empty($plugin)) { $modelName = $plugin . '.' . $modelName; } $modelObj = ClassRegistry::init($modelName, true); if ($modelObj === false) { return false; } $fieldFullName = $modelObj->alias . '.' . $fieldName; $result = compact('modelName', 'fieldName', 'fieldFullName'); return $result; }
php
{ "resource": "" }
q10534
Filter._parseConditionSign
train
protected function _parseConditionSign($conditionSign = null) { $result = ''; if (empty($conditionSign)) { return $result; } $conditionSign = (string)mb_convert_case($conditionSign, MB_CASE_LOWER); switch ($conditionSign) { case 'gt': $result = '>'; break; case 'ge': $result = '>='; break; case 'lt': $result = '<'; break; case 'le': $result = '<='; break; case 'ne': $result = '<>'; break; case 'eq': default: $result = ''; } return $result; }
php
{ "resource": "" }
q10535
Filter._parseConditionGroup
train
protected function _parseConditionGroup($condition = null) { $result = 'AND'; if (empty($condition)) { return $result; } $condition = (string)mb_convert_case($condition, MB_CASE_UPPER); if (in_array($condition, ['AND', 'OR', 'NOT'])) { $result = $condition; } return $result; }
php
{ "resource": "" }
q10536
Filter.buildConditions
train
public function buildConditions($filterData = null, $filterConditions = null, $plugin = null, $limit = CAKE_THEME_FILTER_ROW_LIMIT) { $result = []; if (empty($filterData) || !is_array($filterData)) { return $result; } if (!is_array($filterConditions)) { $filterConditions = []; } $conditionsGroup = null; if (isset($filterConditions['group'])) { $conditionsGroup = $filterConditions['group']; } $conditionSignGroup = $this->_parseConditionGroup($conditionsGroup); $conditionsCache = []; $filterRowCount = 0; $limit = (int)$limit; if ($limit <= 0) { $limit = CAKE_THEME_FILTER_ROW_LIMIT; } foreach ($filterData as $index => $modelInfo) { if (!is_int($index) || !is_array($modelInfo)) { continue; } $filterRowCount++; if ($filterRowCount > $limit) { break; } foreach ($modelInfo as $filterModel => $filterField) { if (!is_array($filterField)) { continue; } foreach ($filterField as $filterFieldName => $filterFieldValue) { if ($filterFieldValue === '') { continue; } $condSign = null; if (isset($filterConditions[$index][$filterModel][$filterFieldName])) { $condSign = $filterConditions[$index][$filterModel][$filterFieldName]; } $condition = $this->getCondition($filterModel . '.' . $filterFieldName, $filterFieldValue, $condSign, $plugin); if ($condition === false) { continue; } $cacheKey = md5(serialize($condition)); if (in_array($cacheKey, $conditionsCache)) { continue; } $result[$conditionSignGroup][] = $condition; $conditionsCache[] = $cacheKey; } } } if (isset($result[$conditionSignGroup]) && (count($result[$conditionSignGroup]) == 1)) { $result = array_shift($result[$conditionSignGroup]); } return $result; }
php
{ "resource": "" }
q10537
Bar.getOptions
train
public function getOptions() { $opts = array(); $first = array(); $second = array(); if ( $this->axisRenderer ) { $first['renderer'] = '#' . $this->axisRenderer . '#'; } if( isset( $this->options['ticks'] ) ) { $first['ticks'] = $this->options['ticks']; } $second['min'] = isset( $this->options['min'] ) ? $this->options['min'] : 0; if( isset( $this->options['horizontal'] ) && $this->options['horizontal'] ) { $opts['xaxis'] = $second; $opts['yaxis'] = $first; } else { $opts['xaxis'] = $first; $opts['yaxis'] = $second; } $opts = array( 'axes' => $opts ); if( isset( $this->options['stackSeries'] ) ) { $opts['stackSeries'] = $this->options['stackSeries']; } if( isset( $this->options['seriesColors'] ) ) { $opts['seriesColors'] = $this->options['seriesColors']; } return $opts; }
php
{ "resource": "" }
q10538
AdminGroupConfiguration.getGroupPermissions
train
public function getGroupPermissions($groupName) { if (!isset($this->config[$groupName])) { return []; } return array_keys($this->config[$groupName]['permissions']); }
php
{ "resource": "" }
q10539
AdminGroupConfiguration.getGroupLabel
train
public function getGroupLabel($groupName) { if (!isset($this->config[$groupName])) { return ""; } return $this->config[$groupName]['label']->get(); }
php
{ "resource": "" }
q10540
Generate.makeMaintenanceFile
train
public function makeMaintenanceFile() { $filePath = $this->downClass->getFilePath(); $template = __DIR__ .'/.maintenance'; return exec('cat '.$template.' > '.$filePath); }
php
{ "resource": "" }
q10541
Player.updateWithScores
train
public function updateWithScores($scores) { // Update the winner player. if (isset($scores['winnerplayer'])) { $player = $this->getPlayer($scores['winnerplayer']); if ($player) { $this->playerQueryBuilder->save($player); } } // Update remaining players. foreach ($this->loggedInPlayers as $player) { $this->updatePlayer($player); } $this->playerQueryBuilder->saveAll($this->loggedInPlayers); }
php
{ "resource": "" }
q10542
Player.updatePlayer
train
protected function updatePlayer($player) { $time = time(); $upTime = $time - $this->playerLastUpTime[$player->getLogin()]; $this->playerLastUpTime[$player->getLogin()] = $time; $player->setOnlineTime($player->getOnlineTime() + $upTime); }
php
{ "resource": "" }
q10543
Player.getPlayer
train
public function getPlayer($login) { if (isset($this->loggedInPlayers[$login])) { return $this->loggedInPlayers[$login]; } return $this->playerQueryBuilder->findByLogin($login); }
php
{ "resource": "" }
q10544
ChartRenderer.render
train
public static function render( Chart $chart, array $styleOptions = array() ) { if ( empty( self::$rendererChain ) ) { self::pushRenderer( '\Altamira\ChartRenderer\DefaultRenderer' ); } $outputString = ''; for ( $i = count( self::$rendererChain ) - 1; $i >= 0; $i-- ) { $renderer = self::$rendererChain[$i]; $outputString .= call_user_func_array( array( $renderer, 'preRender' ), array( $chart, $styleOptions ) ); } for ( $i = 0; $i < count( self::$rendererChain ); $i++ ) { $renderer = self::$rendererChain[$i]; $outputString .= call_user_func_array( array( $renderer, 'postRender' ), array( $chart, $styleOptions ) ); } return $outputString; }
php
{ "resource": "" }
q10545
ChartRenderer.pushRenderer
train
public static function pushRenderer( $renderer ) { if (! in_array( 'Altamira\ChartRenderer\RendererInterface', class_implements( $renderer ) ) ) { throw new \UnexpectedValueException( "Renderer must be instance of or string name of a class implementing RendererInterface" ); } array_push( self::$rendererChain, $renderer ); return self::getInstance(); }
php
{ "resource": "" }
q10546
ChartRenderer.unshiftRenderer
train
public static function unshiftRenderer( $renderer ) { if (! in_array( 'Altamira\ChartRenderer\RendererInterface', class_implements( $renderer ) ) ) { throw new \UnexpectedValueException( "Renderer must be instance of or string name of a class implementing RendererInterface" ); } array_unshift( self::$rendererChain, $renderer ); return self::getInstance(); }
php
{ "resource": "" }
q10547
UserField.createField
train
public function createField($fieldName, $defaultValue = null) { $fieldType = $this->fieldType; $field = $fieldType::create($fieldName, $this->Title, $defaultValue); $field->addExtraClass($this->ExtraClass); $this->extend('updateCreateField', $field); return $field; }
php
{ "resource": "" }
q10548
ManialinkFactory.create
train
public function create($group) { if (is_string($group)) { $group = $this->groupFactory->createForPlayer($group); } else { if (is_array($group)) { $group = $this->groupFactory->createForPlayers($group); } } if (!is_null($this->guiHandler->getManialink($group, $this))) { $this->update($group); return $group; } $ml = $this->createManialink($group); $this->guiHandler->addToDisplay($ml, $this); $this->createContent($ml); $this->updateContent($ml); return $group; }
php
{ "resource": "" }
q10549
ManialinkFactory.update
train
public function update($group) { if (is_string($group)) { $group = $this->groupFactory->createForPlayer($group); } else { if (is_array($group)) { $group = $this->groupFactory->createForPlayers($group); } } $ml = $this->guiHandler->getManialink($group, $this); if ($ml) { $this->actionFactory->destroyNotPermanentActions($ml); if ($ml instanceof Window) { $ml->busyCounter += 1; if ($ml->isBusy && $ml->busyCounter > 1) { $ml->setBusy(false); } } $this->updateContent($ml); $this->guiHandler->addToDisplay($ml, $this); } }
php
{ "resource": "" }
q10550
ManialinkFactory.destroy
train
public function destroy(Group $group) { $ml = $this->guiHandler->getManialink($group, $this); if ($ml) { $this->guiHandler->addToHide($ml, $this); } }
php
{ "resource": "" }
q10551
ManialinkFactory.createManialink
train
protected function createManialink(Group $group) { $className = $this->className; return new $className($this, $group, $this->name, $this->sizeX, $this->sizeY, $this->posX, $this->posY); }
php
{ "resource": "" }
q10552
MxKarmaService.connect
train
public function connect($serverLogin, $apikey) { $this->apiKey = $apikey; $this->serverLogin = $serverLogin; if (empty($this->apiKey)) { $this->console->writeln('MxKarma error: You need to define a api key'); return; } if (empty($this->serverLogin)) { $this->console->writeln('MxKarma error: You need to define server login'); return; } $params = [ "serverLogin" => $serverLogin, "applicationIdentifier" => "eXpansion v ".AbstractApplication::EXPANSION_VERSION, "testMode" => "false", ]; $this->console->writeln('> MxKarma attempting to connect...'); $this->http->get( $this->buildUrl( "startSession", $params), [$this, "xConnect"] ); }
php
{ "resource": "" }
q10553
MxKarmaService.loadVotes
train
public function loadVotes($players = array(), $getVotesOnly = false) { if (!$this->connected) { $this->console->writeln('> MxKarma trying to load votes when not connected: $ff0aborting!'); return; } $this->console->writeln('> MxKarma attempting to load votes...'); $params = array("sessionKey" => $this->sessionKey); $postData = [ "gamemode" => $this->getGameMode(), "titleid" => $this->gameDataStorage->getVersion()->titleId, "mapuid" => $this->mapStorage->getCurrentMap()->uId, "getvotesonly" => $getVotesOnly, "playerlogins" => $players, ]; $this->http->post( $this->buildUrl("getMapRating", $params), json_encode($postData), array($this, "xGetRatings"), [], $this->options ); }
php
{ "resource": "" }
q10554
Gzip.zip
train
public function zip($sSourceFile, $sDestinationFile=null) { if($sDestinationFile === null) $sDestinationFile = $this->getDefaultDestinationFilename($sSourceFile); if(! ($fh = fopen($sSourceFile, 'rb'))) throw new FileOpenException($sSourceFile); if(! ($zp = gzopen($sDestinationFile, 'wb9'))) throw new FileOpenException($sDestinationFile); while(! feof($fh)) { $data = fread($fh, static::READ_SIZE); if(false === $data) throw new FileReadException($sSourceFile); $sz = strlen($data); if($sz !== gzwrite($zp, $data, $sz)) throw new FileWriteException($sDestinationFile); } gzclose($zp); fclose($fh); return $sDestinationFile; }
php
{ "resource": "" }
q10555
Params.error
train
private function error(OutputInterface $output, $message, $args = array()) { /** @noinspection HtmlUnknownTag */ $output->writeln('<error>' . sprintf($message, $args) . '</error>'); exit(0); }
php
{ "resource": "" }
q10556
RequestRememberPasswordController.requestRememberPasswordAction
train
public function requestRememberPasswordAction(Request $request, $userClass) { $form = $this->get('form.factory')->createNamedBuilder('', RequestRememberPasswordType::class, null, [ 'csrf_protection' => false, ])->getForm(); $form->handleRequest($request); if ($form->isValid()) { try { $this->get('bengor_user.' . $userClass . '.api_command_bus')->handle( $form->getData() ); return new JsonResponse(); } catch (UserDoesNotExistException $exception) { return new JsonResponse( sprintf( 'The "%s" user email does not exist ', $form->getData()->email() ), 400 ); } } return new JsonResponse(FormErrorSerializer::errors($form), 400); }
php
{ "resource": "" }
q10557
Session.get
train
public function get($key, $default = null) { if (!$this->id) { throw new Exception('Cannot use get without active session.'); } return array_key_exists($key, $this->data) ? $this->data[$key] : $default; }
php
{ "resource": "" }
q10558
Session.id
train
public function id($id = null) { if ($id) { if (!$this->isValidId($id)) { throw new \InvalidArgumentException('$id may contain only [a-zA-Z0-9-_]'); } if ($this->id) { throw new Exception('Cannot set id while session is active'); } $this->requestedId = $id; } return $this->id; }
php
{ "resource": "" }
q10559
Session.persistedDataExists
train
public function persistedDataExists($id) { if (!$this->id) { $this->handler->open($this->savePath, $this->name); } $ret = (bool)$this->handler->read($id); if (!$this->id) { $this->handler->close(); } return $ret; }
php
{ "resource": "" }
q10560
Session.destroy
train
public function destroy($removeCookie = false) { if ($this->id) { if ($removeCookie) { $this->removeCookie(); } $this->handler->destroy($this->id); $this->handler->close(); $this->id = ''; $this->data = null; return true; } return false; }
php
{ "resource": "" }
q10561
Session.regenerateId
train
public function regenerateId($deleteOldSession = false) { if (headers_sent() || !$this->id) { return false; } $oldId = $this->id; $this->id = IdGenerator::generateSessionId($this->idLength); $this->setCookie($this->name, $this->id); if ($oldId && $deleteOldSession) { $this->handler->destroy($oldId); } return true; }
php
{ "resource": "" }
q10562
Session.removeCookie
train
public function removeCookie() { return setcookie( $this->name, '', time() - 86400, $this->cookie_path, $this->cookie_domain, (bool)$this->cookie_secure, (bool)$this->cookie_httponly ); }
php
{ "resource": "" }
q10563
Session.sendStartHeaders
train
protected function sendStartHeaders() { // send optional cache limiter // this is actual session behavior rather than what's documented. $lastModified = self::formatAsGmt(filemtime($_SERVER['SCRIPT_FILENAME'])); $ce = $this->cache_expire; switch ($this->cache_limiter) { case self::CACHE_LIMITER_PUBLIC: header('Expires: ' . self::formatAsGmt(time() + $ce)); header("Cache-Control: public, max-age=$ce"); header('Last-Modified: ' . $lastModified); break; case self::CACHE_LIMITER_PRIVATE_NO_EXPIRE: header("Cache-Control: private, max-age=$ce, pre-check=$ce"); header('Last-Modified: ' . $lastModified); break; case self::CACHE_LIMITER_PRIVATE: header('Expires: Thu, 19 Nov 1981 08:52:00 GMT'); header("Cache-Control: private, max-age=$ce, pre-check=$ce"); header('Last-Modified: ' . $lastModified); break; case self::CACHE_LIMITER_NOCACHE: header('Expires: Thu, 19 Nov 1981 08:52:00 GMT'); header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); header('Pragma: no-cache'); break; case self::CACHE_LIMITER_NONE: // send no cache headers, please break; } }
php
{ "resource": "" }
q10564
ValidatorDecorator.validate
train
public function validate($value, $constraints = null, $groups = null) { return $this->decoratedValidator->validate($value, $constraints, $groups); }
php
{ "resource": "" }
q10565
ValidatorDecorator.validateProperty
train
public function validateProperty($object, $propertyName, $groups = null) { return $this->decoratedValidator->validateProperty($object, $propertyName, $groups); }
php
{ "resource": "" }
q10566
ValidatorDecorator.validatePropertyValue
train
public function validatePropertyValue($objectOrClass, $propertyName, $value, $groups = null) { return $this->decoratedValidator->validatePropertyValue($objectOrClass, $propertyName, $value, $groups); }
php
{ "resource": "" }
q10567
ViewExtensionComponent.isHtml
train
public function isHtml() { $ext = $this->_controller->request->param('ext'); if (empty($ext)) { return true; } $prefers = $this->_controller->RequestHandler->prefers(); if (empty($prefers)) { $prefers = 'html'; } $responseMimeType = $this->_controller->response->getMimeType($prefers); if (!$responseMimeType) { return false; } return in_array('text/html', (array)$responseMimeType); }
php
{ "resource": "" }
q10568
ViewExtensionComponent._addSpecificResponse
train
protected function _addSpecificResponse(Controller &$controller) { $controller->response->type(['sse' => 'text/event-stream']); $controller->response->type(['mod' => 'text/html']); $controller->response->type(['pop' => 'text/html']); $controller->response->type(['prt' => 'text/html']); }
php
{ "resource": "" }
q10569
ViewExtensionComponent._setUiLangVar
train
protected function _setUiLangVar(Controller &$controller) { $uiLcid2 = $this->_language->getCurrentUiLang(true); $uiLcid3 = $this->_language->getCurrentUiLang(false); $controller->set(compact('uiLcid2', 'uiLcid3')); }
php
{ "resource": "" }
q10570
ViewExtensionComponent._setLayout
train
protected function _setLayout(Controller &$controller) { $isModal = $controller->request->is('modal'); $isPopup = $controller->request->is('popup'); $isSSE = $controller->request->is('sse'); $isPrint = $controller->request->is('print'); if ($isModal || $isPopup || $isSSE) { $controller->layout = 'CakeTheme.default'; } elseif ($isPrint) { $controller->viewPath = mb_ereg_replace(DS . 'prt', '', $controller->viewPath); $controller->response->type('html'); } }
php
{ "resource": "" }
q10571
ViewExtensionComponent._getSessionKeyRedirect
train
protected function _getSessionKeyRedirect($key = null) { if (empty($key)) { $key = $this->_controller->request->here(); } $cacheKey = md5((string)$key); return $cacheKey; }
php
{ "resource": "" }
q10572
ViewExtensionComponent.setRedirectUrl
train
public function setRedirectUrl($redirect = null, $key = null) { if (empty($redirect)) { $redirect = $this->_controller->request->referer(true); } elseif ($redirect === true) { $redirect = $this->_controller->request->here(true); } if (empty($redirect) || $this->_controller->request->is('popup') || $this->_controller->request->is('print')) { return false; } $cacheKey = $this->_getSessionKeyRedirect($key); $data = CakeSession::read($cacheKey); if (!empty($data) && (md5((string)$data) === md5((string)$redirect))) { return false; } return CakeSession::write($cacheKey, $redirect); }
php
{ "resource": "" }
q10573
ViewExtensionComponent._getRedirectCache
train
protected function _getRedirectCache($key = null) { $cacheKey = $this->_getSessionKeyRedirect($key); $redirect = CakeSession::consume($cacheKey); return $redirect; }
php
{ "resource": "" }
q10574
ViewExtensionComponent.getRedirectUrl
train
public function getRedirectUrl($defaultRedirect = null, $key = null) { $redirect = $this->_getRedirectCache($key); if (empty($redirect)) { if (!empty($defaultRedirect)) { if ($defaultRedirect === true) { $redirect = $this->_controller->request->here(); } else { $redirect = $defaultRedirect; } } else { $redirect = ['action' => 'index']; } } return $redirect; }
php
{ "resource": "" }
q10575
ViewExtensionComponent.redirectByUrl
train
public function redirectByUrl($defaultRedirect = null, $key = null) { $redirectUrl = $this->getRedirectUrl($defaultRedirect, $key); return $this->_controller->redirect($redirectUrl); }
php
{ "resource": "" }
q10576
ViewExtensionComponent._setLocale
train
protected function _setLocale() { $language = $this->_language->getCurrentUiLang(false); return (bool)setlocale(LC_ALL, $language); }
php
{ "resource": "" }
q10577
ViewExtensionComponent.setProgressSseTask
train
public function setProgressSseTask($taskName = null) { if (empty($taskName)) { return false; } $tasks = (array)CakeSession::read('SSE.progress'); if (in_array($taskName, $tasks)) { return true; } $tasks[] = $taskName; return CakeSession::write('SSE.progress', $tasks); }
php
{ "resource": "" }
q10578
ViewExtensionComponent.setExceptionMessage
train
public function setExceptionMessage($message = '', $defaultRedirect = null, $key = null) { $statusCode = null; $redirectUrl = null; if ($message instanceof Exception) { if ($this->_controller->request->is('ajax')) { $statusCode = $message->getCode(); } } if (empty($statusCode)) { $this->_controller->Flash->error($message); $redirectUrl = $this->getRedirectUrl($defaultRedirect, $key); } return $this->_controller->redirect($redirectUrl, $statusCode); }
php
{ "resource": "" }
q10579
ScriptSettingsWindowFactory.callbackApply
train
public function callbackApply(ManialinkInterface $manialink, $login, $entries, $args) { /** @var GridBuilder $grid */ $grid = $manialink->getData('grid'); $grid->updateDataCollection($entries); // update datacollection // build settings array from datacollection $settings = []; foreach ($grid->getDataCollection()->getAll() as $key => $value) { $settings[$value['name']] = $value['value']; } try { $this->factory->getConnection()->setModeScriptSettings($settings); $this->closeManialink($manialink); } catch (\Exception $ex) { // TODO this should use chat notification. $this->factory->getConnection()->chatSendServerMessage("error: ".$ex->getMessage()); $this->console->writeln('$f00Error: $fff'.$ex->getMessage()); } }
php
{ "resource": "" }
q10580
ScriptSettingsWindowFactory.fetchScriptSettings
train
public function fetchScriptSettings() { $data = []; $scriptSettings = $this->factory->getConnection()->getModeScriptSettings(); /** * @var string $i */ $i = 1; foreach ($scriptSettings as $name => $value) { $data[] = [ 'index' => $i++, 'name' => $name, 'value' => $value, ]; } return $data; }
php
{ "resource": "" }
q10581
DedimaniaService.processRecord
train
public function processRecord($login, $score, $checkpoints) { if ($this->enabled->get() == false) { return false; } if ($this->isDisabled()) { return false; } $tempRecords = $this->recordsByLogin; $tempPositions = $this->ranksByLogin; if (isset($this->recordsByLogin[$login])) { $record = $this->recordsByLogin[$login]; } else { $record = new DedimaniaRecord($login); $pla = $this->playerStorage->getPlayerInfo($login); $record->nickName = $pla->getNickName(); } $tempRecords[$login] = clone $record; $oldRecord = clone $record; // if better time if ($score < $oldRecord->best || $oldRecord->best == -1) { $record->best = $score; $record->checks = implode(",", $checkpoints); $tempRecords[$login] = $record; // sort and update new rank uasort($tempRecords, [$this, "compare"]); if (!isset($this->players[$login])) { echo "player $login not connected\n"; return false; } $player = $this->players[$login]; // recalculate ranks for records $rank = 1; $newRecord = false; foreach ($tempRecords as $key => $tempRecord) { $tempRecords[$key]->rank = $rank; $tempPositions[$key] = $rank; if ($tempRecord->login == $login && ($rank <= $this->serverMaxRank || $rank <= $player->maxRank) && $rank < 100) { $newRecord = $tempRecords[$login]; } $rank++; } $tempRecords = array_slice($tempRecords, 0, 100, true); $tempPositions = array_slice($tempPositions, 0, 100, true); if ($newRecord) { $this->recordsByLogin = $tempRecords; $outRecords = usort($tempRecords, [$this, 'compare']); $this->ranksByLogin = $tempPositions; $params = [ $newRecord, $oldRecord, $outRecords, $newRecord->rank, $oldRecord->rank, ]; $this->dispatcher->dispatch("expansion.dedimania.records.update", [$params]); return $newRecord; } } return false; }
php
{ "resource": "" }
q10582
VoteManager.onVoteNew
train
public function onVoteNew(Player $player, $cmdName, $cmdValue) { if ($cmdValue instanceof Vote) { $this->updateVoteWidgetFactory->create($this->players); $this->voteWidgetFactory->create($this->players); } else { $this->voteService->startVote($player, $cmdName, ['value' => $cmdValue]); } }
php
{ "resource": "" }
q10583
VoteManager.onVoteCancelled
train
public function onVoteCancelled(Player $player, $cmdName, $cmdValue) { if ($cmdValue instanceof Vote) { $this->voteWidgetFactory->destroy($this->players); $this->updateVoteWidgetFactory->destroy($this->players); } else { $this->voteService->cancel(); } }
php
{ "resource": "" }
q10584
VoteManager.onVoteNo
train
public function onVoteNo(Player $player, $vote) { if ($this->voteService->getCurrentVote() instanceof AbstractVotePlugin) { $this->updateVoteWidgetFactory->updateVote($vote); } }
php
{ "resource": "" }
q10585
MoveBehavior._getBehaviorConfig
train
protected function _getBehaviorConfig(Model $model, $configParam = null) { if (empty($configParam) || !isset($model->Behaviors->Tree->settings[$model->alias][$configParam])) { return null; } $result = $model->Behaviors->Tree->settings[$model->alias][$configParam]; return $result; }
php
{ "resource": "" }
q10586
MoveBehavior._changeParent
train
protected function _changeParent(Model $model, $id = null, $parentId = null) { $parentField = $this->_getBehaviorConfig($model, 'parent'); if (empty($id) || ($parentField === null)) { return false; } $model->recursive = -1; $treeItem = $model->read(null, $id); if (empty($treeItem)) { return false; } $treeItem[$model->alias][$parentField] = $parentId; $result = (bool)$model->save($treeItem); return $result; }
php
{ "resource": "" }
q10587
MoveBehavior._getSubTree
train
protected function _getSubTree(Model $model, $id = null) { $result = []; $parentField = $this->_getBehaviorConfig($model, 'parent'); $leftField = $this->_getBehaviorConfig($model, 'left'); if (($parentField === null) || ($leftField === null)) { return $result; } $conditions = [ $model->alias . '.' . $parentField => null ]; if (!empty($id)) { $conditions[$model->alias . '.' . $parentField] = (int)$id; } if ($model->Behaviors->Tree->settings[$model->alias]['scope'] !== '1 = 1') { $conditions[] = $model->Behaviors->Tree->settings[$model->alias]['scope']; } $fields = [ $model->alias . '.' . $model->primaryKey, ]; $order = [ $model->alias . '.' . $leftField => 'asc' ]; $model->recursive = -1; $data = $model->find('list', compact('conditions', 'fields', 'order')); if (!empty($data)) { $result = array_keys($data); } return $result; }
php
{ "resource": "" }
q10588
MoveBehavior.moveItem
train
public function moveItem(Model $model, $direct = null, $id = null, $delta = 1) { $direct = mb_strtolower($direct); $delta = (int)$delta; if (in_array($direct, ['up', 'down']) && ($delta < 0)) { throw new InternalErrorException(__d('view_extension', 'Invalid delta for moving record')); } if (!in_array($direct, ['top', 'up', 'down', 'bottom'])) { throw new InternalErrorException(__d('view_extension', 'Invalid direction for moving record')); } switch ($direct) { case 'top': $delta = true; // no break case 'up': $method = 'moveUp'; break; case 'bottom': $delta = true; // no break case 'down': $method = 'moveDown'; break; } $newParentId = null; $optionsEvent = compact('id', 'newParentId', 'method', 'delta'); $event = new CakeEvent('Model.beforeUpdateTree', $model, [$optionsEvent]); $model->getEventManager()->dispatch($event); if ($event->isStopped()) { return false; } $result = $model->$method($id, $delta); if ($result) { $event = new CakeEvent('Model.afterUpdateTree', $model); $model->getEventManager()->dispatch($event); } return $result; }
php
{ "resource": "" }
q10589
MoveBehavior.moveDrop
train
public function moveDrop(Model $model, $id = null, $newParentId = null, $oldParentId = null, $dropData = null) { if (empty($id)) { return false; } $changeRoot = false; $dataSource = $model->getDataSource(); $dataSource->begin(); if ($newParentId != $oldParentId) { $changeRoot = true; if (!$this->_changeParent($model, $id, $newParentId)) { $dataSource->rollback(); return false; } } $newDataList = []; if (!empty($dropData) && is_array($dropData)) { $newDataList = Hash::extract($dropData, '0.{n}.id'); } $oldDataList = $this->_getSubTree($model, $newParentId); if ($newDataList == $oldDataList) { if (!$changeRoot) { return true; } $dataSource->rollback(); return false; } $indexNew = array_search($id, $newDataList); $indexOld = array_search($id, $oldDataList); if (($indexNew === false) || ($indexOld === false)) { return false; } $delta = $indexNew - $indexOld; $method = 'moveDown'; if ($delta < 0) { $delta *= -1; $method = 'moveUp'; } $optionsEvent = compact('id', 'newParentId', 'method', 'delta'); $event = new CakeEvent('Model.beforeUpdateTree', $model, [$optionsEvent]); $model->getEventManager()->dispatch($event); if ($event->isStopped()) { $dataSource->rollback(); return false; } $result = $model->$method($id, $delta); if ($result) { $dataSource->commit(); $event = new CakeEvent('Model.afterUpdateTree', $model); $model->getEventManager()->dispatch($event); } else { $dataSource->rollback(); } return $result; }
php
{ "resource": "" }
q10590
Assets._wp_oembed_blog_card_render
train
public function _wp_oembed_blog_card_render() { if ( empty( $_GET['url'] ) ) { return; } header( 'Content-Type: text/html; charset=utf-8' ); $url = esc_url_raw( wp_unslash( $_GET['url'] ) ); echo wp_kses_post( View::get_template( $url ) ); die(); }
php
{ "resource": "" }
q10591
PeriodManager.getLastPeriodOfFiscalYear
train
public function getLastPeriodOfFiscalYear(array $input) { $period = $this->Period->lastPeriodbyOrganizationAndByFiscalYear($this->AuthenticationManager->getCurrentUserOrganizationId(), $input['id'])->toArray(); $period['endDate'] = $this->Carbon->createFromFormat('Y-m-d', $period['end_date'])->format($this->Lang->get('form.phpShortDateFormat')); unset($period['end_date']); $period['month'] = $period['month'] . ' - ' . $this->Lang->get('decima-accounting::period-management.' . $period['month']); return json_encode($period); }
php
{ "resource": "" }
q10592
PeriodManager.getCurrentMonthPeriod
train
public function getCurrentMonthPeriod($organizationId = null) { if(empty($organizationId)) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganization('id'); } $fiscalYearId = $this->FiscalYear->lastFiscalYearByOrganization($organizationId); $Date = new Carbon('first day of this month'); $Date2 = new Carbon('last day of this month'); return $this->Period->periodByStardDateByEndDateByFiscalYearAndByOrganizationId($Date->format('Y-m-d'), $Date2->format('Y-m-d'), $fiscalYearId, $organizationId); }
php
{ "resource": "" }
q10593
PeriodManager.getPeriodByDateAndByOrganizationId
train
public function getPeriodByDateAndByOrganizationId($date, $organizationId = null, $databaseConnectionName = null) { if(empty($organizationId)) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganization('id'); } return $this->Period->periodByDateAndByOrganizationId($date, $organizationId, $databaseConnectionName); }
php
{ "resource": "" }
q10594
PeriodManager.getBalanceAccountsClosingPeriods
train
public function getBalanceAccountsClosingPeriods(array $input) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganization('id'); $fiscalYearId = $this->FiscalYear->lastFiscalYearByOrganization($organizationId); if($fiscalYearId == $input['id']) { return json_encode(array('info' => $this->Lang->get('decima-accounting::period-management.invalidFiscalYear'))); } $period = json_decode($this->getLastPeriodOfFiscalYear($input), true); $FiscalYear = $this->FiscalYear->byId($input['id']); $FiscalYear = $this->FiscalYear->byYearAndByOrganization($FiscalYear->year + 1, $organizationId); $period2 = $this->Period->firstPeriodbyOrganizationAndByFiscalYear($this->AuthenticationManager->getCurrentUserOrganizationId(), $FiscalYear->id)->toArray(); $period2['endDate'] = $this->Carbon->createFromFormat('Y-m-d', $period2['end_date'])->format($this->Lang->get('form.phpShortDateFormat')); unset($period2['end_date']); $period2['month'] = $period2['month'] . ' - ' . $this->Lang->get('decima-accounting::period-management.' . $period2['month']); return json_encode(array('id0' => $period['id'], 'month0' => $period['month'], 'endDate0' => $period['endDate'], 'id1' => $period2['id'], 'month1' => $period2['month'], 'endDate1' => $period2['endDate'], 'fiscalYearId' => $FiscalYear->id)); }
php
{ "resource": "" }
q10595
PeriodManager.openPeriod
train
public function openPeriod(array $input) { $this->DB->transaction(function() use ($input) { $loggedUserId = $this->AuthenticationManager->getLoggedUserId(); $organizationId = $this->AuthenticationManager->getCurrentUserOrganization('id'); $Period = $this->Period->byId($input['id']); $Journal = $this->Journal->create(array('journalized_id' => $input['id'], 'journalized_type' => $this->Period->getTable(), 'user_id' => $loggedUserId, 'organization_id' => $organizationId)); // $this->Journal->attachDetail($Journal->id, array('field' => $this->Lang->get('decima-accounting::journal-management.status'), 'field_lang_key' => 'decima-accounting::journal-management.status', 'old_value' => $this->Lang->get('decima-accounting::period-management.closed'), 'new_value' => $this->Lang->get('decima-accounting::period-management.opened')), $Journal); $this->Journal->attachDetail($Journal->id, array('note' => $this->Lang->get('decima-accounting::period-management.periodOpenedJournal', array('period' => $this->Lang->get('decima-accounting::period-management.' . $Period->month))), $Journal)); $this->Period->update(array('is_closed' => false), $Period); }); return json_encode(array('success' => $this->Lang->get('form.defaultSuccessOperationMessage'), 'periods' => $this->getPeriods(), 'periodsFilter' => $this->getPeriods2())); }
php
{ "resource": "" }
q10596
PeriodManager.closePeriod
train
public function closePeriod(array $input) { $canBeClosed = true; $this->DB->transaction(function() use ($input, &$canBeClosed) { $loggedUserId = $this->AuthenticationManager->getLoggedUserId(); $organizationId = $this->AuthenticationManager->getCurrentUserOrganization('id'); if($this->JournalVoucher->getByOrganizationByPeriodAndByStatus($organizationId, array($input['id']), 'A')->count() > 0) { $canBeClosed = false; return; } $Period = $this->Period->byId($input['id']); $Journal = $this->Journal->create(array('journalized_id' => $input['id'], 'journalized_type' => $this->Period->getTable(), 'user_id' => $loggedUserId, 'organization_id' => $organizationId)); // $this->Journal->attachDetail($Journal->id, array('field' => $this->Lang->get('decima-accounting::journal-management.status'), 'field_lang_key' => 'decima-accounting::journal-management.status', 'old_value' => $this->Lang->get('decima-accounting::period-management.opened'), 'new_value' => $this->Lang->get('decima-accounting::period-management.closed')), $Journal); $this->Journal->attachDetail($Journal->id, array('note' => $this->Lang->get('decima-accounting::period-management.periodClosedJournal', array('period' => $this->Lang->get('decima-accounting::period-management.' . $Period->month))), $Journal)); $this->Period->update(array('is_closed' => true), $Period); }); if(!$canBeClosed) { return json_encode(array('success' => false, 'info' => $this->Lang->get('decima-accounting::period-management.voucherException'))); } return json_encode(array('success' => $this->Lang->get('form.defaultSuccessOperationMessage'), 'periods' => $this->getPeriods(), 'periodsFilter' => $this->getPeriods2())); }
php
{ "resource": "" }
q10597
OAuthRequest.get_signable_parameters
train
public function get_signable_parameters() {/*{{{*/ // Grab all parameters $params = $this->parameters; // Remove oauth_signature if present if (isset($params['oauth_signature'])) { unset($params['oauth_signature']); } // Urlencode both keys and values $keys = OAuthUtil::urlencode_rfc3986(array_keys($params)); $values = OAuthUtil::urlencode_rfc3986(array_values($params)); $params = array_combine($keys, $values); // Sort by keys (natsort) uksort($params, 'strcmp'); // Generate key=value pairs $pairs = array(); foreach ($params as $key=>$value ) { if (is_array($value)) { // If the value is an array, it's because there are multiple // with the same key, sort them, then add all the pairs natsort($value); foreach ($value as $v2) { $pairs[] = $key . '=' . $v2; } } else { $pairs[] = $key . '=' . $value; } } // Return the pairs, concated with & return implode('&', $pairs); }
php
{ "resource": "" }
q10598
OAuthRequest.to_postdata
train
public function to_postdata() {/*{{{*/ $total = array(); foreach ($this->parameters as $k => $v) { if (is_array($v)) { foreach ($v as $va) { $total[] = OAuthUtil::urlencode_rfc3986($k) . "[]=" . OAuthUtil::urlencode_rfc3986($va); } } else { $total[] = OAuthUtil::urlencode_rfc3986($k) . "=" . OAuthUtil::urlencode_rfc3986($v); } } $out = implode("&", $total); return $out; }
php
{ "resource": "" }
q10599
EmbeddedEntityListAttribute.buildValidationRules
train
protected function buildValidationRules() { $rules = new RuleList(); $options = $this->getOptions(); $options[self::OPTION_ENTITY_TYPES] = $this->getEmbeddedEntityTypeMap(); $rules->push( new EmbeddedEntityListRule('valid-embedded-entity-list-data', $options) ); return $rules; }
php
{ "resource": "" }