_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q6400
SplashCore.router
train
public static function router() { if (isset(self::core()->router)) { return self::core()->router; } //====================================================================// // Initialize Tasks List self::core()->router = new Router(); return self::core()->router; }
php
{ "resource": "" }
q6401
SplashCore.file
train
public static function file() { if (!isset(self::core()->file)) { //====================================================================// // Initialize Tasks List self::core()->file = new FileManager(); //====================================================================// // Load Translation File self::translator()->load('file'); } return self::core()->file; }
php
{ "resource": "" }
q6402
SplashCore.validate
train
public static function validate() { if (isset(self::core()->valid)) { return self::core()->valid; } //====================================================================// // Initialize Tasks List self::core()->valid = new Validator(); //====================================================================// // Load Translation File self::translator()->load('ws'); self::translator()->load('validate'); return self::core()->valid; }
php
{ "resource": "" }
q6403
SplashCore.xml
train
public static function xml() { if (isset(self::core()->xml)) { return self::core()->xml; } //====================================================================// // Initialize Tasks List self::core()->xml = new XmlManager(); return self::core()->xml; }
php
{ "resource": "" }
q6404
SplashCore.translator
train
public static function translator() { if (!isset(self::core()->translator)) { //====================================================================// // Initialize Tasks List self::core()->translator = new Translator(); } return self::core()->translator; }
php
{ "resource": "" }
q6405
SplashCore.local
train
public static function local() { //====================================================================// // Initialize Local Core Management Class if (isset(self::core()->localcore)) { return self::core()->localcore; } //====================================================================// // Verify Local Core Class Exist & is Valid if (!self::validate()->isValidLocalClass()) { throw new Exception('You requested access to Local Class, but it is Invalid...'); } //====================================================================// // Initialize Class self::core()->localcore = new Local(); //====================================================================// // Load Translation File self::translator()->load('local'); //====================================================================// // Load Local Includes self::core()->localcore->Includes(); //====================================================================// // Return Local Class return self::core()->localcore; }
php
{ "resource": "" }
q6406
SplashCore.object
train
public static function object($objectType) { //====================================================================// // First Access to Local Objects if (!isset(self::core()->objects)) { //====================================================================// // Initialize Local Objects Class Array self::core()->objects = array(); } //====================================================================// // Check in Cache if (array_key_exists($objectType, self::core()->objects)) { return self::core()->objects[$objectType]; } //====================================================================// // Verify if Object Class is Valid if (!self::validate()->isValidObject($objectType)) { throw new Exception('You requested access to an Invalid Object Type : '.$objectType); } //====================================================================// // Check if Object Manager is Overriden if (self::local() instanceof ObjectsProviderInterface) { //====================================================================// // Initialize Local Object Manager self::core()->objects[$objectType] = self::local()->object($objectType); } else { //====================================================================// // Initialize Standard Class $className = SPLASH_CLASS_PREFIX.'\\Objects\\'.$objectType; self::core()->objects[$objectType] = new $className(); } //====================================================================// // Load Translation File self::translator()->load('objects'); return self::core()->objects[$objectType]; }
php
{ "resource": "" }
q6407
SplashCore.widget
train
public static function widget($widgetType) { //====================================================================// // First Access to Local Objects if (!isset(self::core()->widgets)) { //====================================================================// // Initialize Local Widget Class Array self::core()->widgets = array(); } //====================================================================// // Check in Cache if (array_key_exists($widgetType, self::core()->widgets)) { return self::core()->widgets[$widgetType]; } //====================================================================// // Verify if Widget Class is Valid if (!self::validate()->isValidWidget($widgetType)) { throw new Exception('You requested access to an Invalid Widget Type : '.$widgetType); } //====================================================================// // Check if Widget Manager is Overriden if (self::local() instanceof WidgetsProviderInterface) { //====================================================================// // Initialize Local Widget Manager self::core()->widgets[$widgetType] = self::local()->widget($widgetType); } else { //====================================================================// // Initialize Class $className = SPLASH_CLASS_PREFIX.'\\Widgets\\'.$widgetType; self::core()->widgets[$widgetType] = new $className(); } //====================================================================// // Load Translation File self::translator()->load('widgets'); return self::core()->widgets[$widgetType]; }
php
{ "resource": "" }
q6408
SplashCore.configurator
train
public static function configurator() { //====================================================================// // Configuration Array Already Exists //====================================================================// if (isset(self::core()->configurator)) { return self::core()->configurator; } //====================================================================// // Load Configurator Class Name from Configuration $className = self::configuration()->Configurator; //====================================================================// // No Configurator Defined if (!is_string($className) || empty($className)) { return new NullConfigurator(); } //====================================================================// // Validate Configurator Class Name if (false == self::validate()->isValidConfigurator($className)) { return new NullConfigurator(); } //====================================================================// // Initialize Configurator self::core()->configurator = new $className(); return self::core()->configurator; }
php
{ "resource": "" }
q6409
SplashCore.reboot
train
public static function reboot() { //====================================================================// // Clear Module Configuration Array if (isset(self::core()->conf)) { self::core()->conf = null; } //====================================================================// // Clear Webservice Configuration if (isset(self::core()->soap)) { self::core()->soap = null; } //====================================================================// // Clear Module Local Objects Classes if (isset(self::core()->objects)) { self::core()->objects = null; } //====================================================================// // Clear Module Log self::log()->cleanLog(); self::log()->deb('Splash Module Rebooted'); }
php
{ "resource": "" }
q6410
SplashCore.getLocalPath
train
public static function getLocalPath() { //====================================================================// // Safety Check => Verify Local Class is Valid if (null == self::local()) { return null; } //====================================================================// // Create A Reflection Class of Local Class $reflector = new \ReflectionClass(get_class(self::local())); //====================================================================// // Return Class Local Path return dirname((string) $reflector->getFileName()); }
php
{ "resource": "" }
q6411
SplashCore.input
train
public static function input($name, $type = INPUT_SERVER) { //====================================================================// // Standard Safe Reading $result = filter_input($type, $name); if (null !== $result) { return $result; } //====================================================================// // Fallback Reading if ((INPUT_SERVER === $type) && isset($_SERVER[$name])) { return $_SERVER[$name]; } if ((INPUT_GET === $type) && isset($_GET[$name])) { return $_GET[$name]; } return null; }
php
{ "resource": "" }
q6412
SplashCore.informations
train
public static function informations() { //====================================================================// // Init Response Object $response = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); //====================================================================// // Server General Description $response->shortdesc = SPLASH_NAME.' '.SPLASH_VERSION; $response->longdesc = SPLASH_DESC; //====================================================================// // Company Informations $response->company = null; $response->address = null; $response->zip = null; $response->town = null; $response->country = null; $response->www = null; $response->email = null; $response->phone = null; //====================================================================// // Server Logo & Ico $response->icoraw = self::file()->readFileContents( dirname(dirname(__FILE__)).'/img/Splash-ico.png' ); $response->logourl = null; $response->logoraw = self::file()->readFileContents( dirname(dirname(__FILE__)).'/img/Splash-ico.jpg' ); //====================================================================// // Server Informations $response->servertype = SPLASH_NAME; $response->serverurl = filter_input(INPUT_SERVER, 'SERVER_NAME'); //====================================================================// // Module Informations $response->moduleauthor = SPLASH_AUTHOR; $response->moduleversion = SPLASH_VERSION; //====================================================================// // Verify Local Module Class Is Valid if (!self::validate()->isValidLocalClass()) { return $response; } //====================================================================// // Merge Informations with Local Module Informations $localArray = self::local()->informations($response); if (!($localArray instanceof ArrayObject)) { $response = $localArray; } return $response; }
php
{ "resource": "" }
q6413
SplashCore.objects
train
public static function objects() { //====================================================================// // Check if Object Manager is Overriden if (self::local() instanceof ObjectsProviderInterface) { return self::local()->objects(); } $objectsList = array(); //====================================================================// // Safety Check => Verify Objects Folder Exists $path = self::getLocalPath().'/Objects'; if (!is_dir($path)) { return $objectsList; } //====================================================================// // Scan Local Objects Folder $scan = scandir($path, 1); if (false == $scan) { return $objectsList; } //====================================================================// // Scan Each File in Folder $files = array_diff($scan, array('..', '.', 'index.php', 'index.html')); foreach ($files as $filename) { //====================================================================// // Verify Filename is a File (Not a Directory) if (!is_file($path.'/'.$filename)) { continue; } //====================================================================// // Extract Class Name $className = pathinfo($path.'/'.$filename, PATHINFO_FILENAME); //====================================================================// // Verify ClassName is a Valid Object File if (false == self::validate()->isValidObject($className)) { continue; } $objectsList[] = $className; } return $objectsList; }
php
{ "resource": "" }
q6414
SplashCore.widgets
train
public static function widgets() { //====================================================================// // Check if Widget Manager is Overriden if (self::local() instanceof WidgetsProviderInterface) { return self::local()->widgets(); } $widgetTypes = array(); //====================================================================// // Safety Check => Verify Objects Folder Exists $path = self::getLocalPath().'/Widgets'; if (!is_dir($path)) { return $widgetTypes; } //====================================================================// // Scan Local Objects Folder $scan = scandir($path, 1); if (false == $scan) { return $widgetTypes; } //====================================================================// // Scan Each File in Folder $files = array_diff($scan, array('..', '.', 'index.php', 'index.html')); foreach ($files as $filename) { $className = pathinfo($path.'/'.$filename, PATHINFO_FILENAME); //====================================================================// // Verify ClassName is a Valid Object File if (false == self::validate()->isValidWidget($className)) { continue; } $widgetTypes[] = $className; } return $widgetTypes; }
php
{ "resource": "" }
q6415
nusoap_base.serializeEnvelope
train
public function serializeEnvelope($body, $headers = false, $namespaces = array(), $style = 'rpc', $use = 'encoded', $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/') { // TODO: add an option to automatically run utf8_encode on $body and $headers // if $this->soap_defencoding is UTF-8. Not doing this automatically allows // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1 $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle"); $this->debug("headers:"); $this->appendDebug($this->varDump($headers)); $this->debug("namespaces:"); $this->appendDebug($this->varDump($namespaces)); // serialize namespaces $ns_string = ''; foreach (array_merge($this->namespaces, $namespaces) as $k => $v) { $ns_string .= " xmlns:$k=\"$v\""; } if ($encodingStyle) { $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string"; } // serialize headers if ($headers) { if (is_array($headers)) { $xml = ''; foreach ($headers as $k => $v) { if (is_object($v) && get_class($v) == 'soapval') { $xml .= $this->serialize_val($v, false, false, false, false, false, $use); } else { $xml .= $this->serialize_val($v, $k, false, false, false, false, $use); } } $headers = $xml; $this->debug("In serializeEnvelope, serialized array of headers to $headers"); } $headers = "<SOAP-ENV:Header>" . $headers . "</SOAP-ENV:Header>"; } // serialize envelope return '<?xml version="1.0" encoding="' . $this->soap_defencoding . '"?' . ">" . '<SOAP-ENV:Envelope' . $ns_string . ">" . $headers . "<SOAP-ENV:Body>" . $body . "</SOAP-ENV:Body>" . "</SOAP-ENV:Envelope>"; }
php
{ "resource": "" }
q6416
nusoap_fault.serialize
train
public function serialize() { $ns_string = ''; foreach ($this->namespaces as $k => $v) { $ns_string .= "\n xmlns:$k=\"$v\""; } $return_msg = '<?xml version="1.0" encoding="' . $this->soap_defencoding . '"?>' . '<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"' . $ns_string . ">\n" . '<SOAP-ENV:Body>' . '<SOAP-ENV:Fault>' . $this->serialize_val($this->faultcode, 'faultcode') . $this->serialize_val($this->faultactor, 'faultactor') . $this->serialize_val($this->faultstring, 'faultstring') . $this->serialize_val($this->faultdetail, 'detail') . '</SOAP-ENV:Fault>' . '</SOAP-ENV:Body>' . '</SOAP-ENV:Envelope>'; return $return_msg; }
php
{ "resource": "" }
q6417
nusoap_xmlschema.parseString
train
public function parseString($xml, $type) { // parse xml string if ($xml != "") { // Create an XML parser. $this->parser = xml_parser_create(); // Set the options for parsing the XML data. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); // Set the object for the parser. xml_set_object($this->parser, $this); // Set the element handlers for the parser. if ($type == "schema") { xml_set_element_handler($this->parser, 'schemaStartElement', 'schemaEndElement'); xml_set_character_data_handler($this->parser, 'schemaCharacterData'); } elseif ($type == "xml") { xml_set_element_handler($this->parser, 'xmlStartElement', 'xmlEndElement'); xml_set_character_data_handler($this->parser, 'xmlCharacterData'); } // Parse the XML file. if (!xml_parse($this->parser, $xml, true)) { // Display an error message. $errstr = sprintf( 'XML error parsing XML schema on line %d: %s', xml_get_current_line_number($this->parser), xml_error_string(xml_get_error_code($this->parser)) ); $this->debug($errstr); $this->debug("XML payload:\n" . $xml); $this->setError($errstr); } xml_parser_free($this->parser); } else { $this->debug('no xml passed to parseString()!!'); $this->setError('no xml passed to parseString()!!'); } }
php
{ "resource": "" }
q6418
nusoap_xmlschema.CreateTypeName
train
public function CreateTypeName($ename) { $scope = ''; for ($i = 0; $i < count($this->complexTypeStack); $i++) { $scope .= $this->complexTypeStack[$i] . '_'; } return $scope . $ename . '_ContainedType'; }
php
{ "resource": "" }
q6419
nusoap_xmlschema.addElement
train
public function addElement($attrs) { if (!$this->getPrefix($attrs['type'])) { $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type']; } $this->elements[$attrs['name']] = $attrs; $this->elements[$attrs['name']]['typeClass'] = 'element'; $this->xdebug("addElement " . $attrs['name']); $this->appendDebug($this->varDump($this->elements[$attrs['name']])); }
php
{ "resource": "" }
q6420
soapval.serialize
train
public function serialize($use = 'encoded') { return $this->serialize_val($this->value, $this->name, $this->type, $this->element_ns, $this->type_ns, $this->attributes, $use, true); }
php
{ "resource": "" }
q6421
soap_transport_http.setCurlOption
train
public function setCurlOption($option, $value) { $this->debug("setCurlOption option=$option, value="); $this->appendDebug($this->varDump($value)); curl_setopt($this->ch, $option, $value); }
php
{ "resource": "" }
q6422
soap_transport_http.unsetHeader
train
public function unsetHeader($name) { if (isset($this->outgoing_headers[$name])) { $this->debug("unset header $name"); unset($this->outgoing_headers[$name]); } }
php
{ "resource": "" }
q6423
wsdl.addComplexType
train
public function addComplexType($name, $typeClass = 'complexType', $phpType = 'array', $compositor = '', $restrictionBase = '', $elements = array(), $attrs = array(), $arrayType = '') { if (count($elements) > 0) { $eElements = array(); foreach ($elements as $n => $e) { // expand each element $ee = array(); foreach ($e as $k => $v) { $k = strpos($k, ':') ? $this->expandQname($k) : $k; $v = strpos($v, ':') ? $this->expandQname($v) : $v; $ee[$k] = $v; } $eElements[$n] = $ee; } $elements = $eElements; } if (count($attrs) > 0) { foreach ($attrs as $n => $a) { // expand each attribute foreach ($a as $k => $v) { $k = strpos($k, ':') ? $this->expandQname($k) : $k; $v = strpos($v, ':') ? $this->expandQname($v) : $v; $aa[$k] = $v; } $eAttrs[$n] = $aa; } $attrs = $eAttrs; } $restrictionBase = strpos($restrictionBase, ':') ? $this->expandQname($restrictionBase) : $restrictionBase; $arrayType = strpos($arrayType, ':') ? $this->expandQname($arrayType) : $arrayType; $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; $this->schemas[$typens][0]->addComplexType($name, $typeClass, $phpType, $compositor, $restrictionBase, $elements, $attrs, $arrayType); }
php
{ "resource": "" }
q6424
nusoap_client.checkWSDL
train
public function checkWSDL() { $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); $this->debug('checkWSDL'); // catch errors if ($errstr = $this->wsdl->getError()) { $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); $this->debug('got wsdl error: ' . $errstr); $this->setError('wsdl error: ' . $errstr); } elseif ($this->operations = $this->wsdl->getOperations($this->portName, 'soap')) { $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); $this->bindingType = 'soap'; $this->debug('got ' . count($this->operations) . ' operations from wsdl ' . $this->wsdlFile . ' for binding type ' . $this->bindingType); } elseif ($this->operations = $this->wsdl->getOperations($this->portName, 'soap12')) { $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); $this->bindingType = 'soap12'; $this->debug('got ' . count($this->operations) . ' operations from wsdl ' . $this->wsdlFile . ' for binding type ' . $this->bindingType); $this->debug('**************** WARNING: SOAP 1.2 BINDING *****************'); } else { $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); $this->debug('getOperations returned false'); $this->setError('no operations defined in the WSDL document!'); } }
php
{ "resource": "" }
q6425
nusoap_client.loadWSDL
train
public function loadWSDL() { $this->debug('instantiating wsdl class with doc: ' . $this->wsdlFile); $this->wsdl = new wsdl('', $this->proxyhost, $this->proxyport, $this->proxyusername, $this->proxypassword, $this->timeout, $this->response_timeout, $this->curl_options, $this->use_curl); $this->wsdl->setCredentials($this->username, $this->password, $this->authtype, $this->certRequest); $this->wsdl->fetchWSDL($this->wsdlFile); $this->checkWSDL(); }
php
{ "resource": "" }
q6426
nusoap_client.checkCookies
train
public function checkCookies() { if (sizeof($this->cookies) == 0) { return true; } $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies'); $curr_cookies = $this->cookies; $this->cookies = array(); foreach ($curr_cookies as $cookie) { if (!is_array($cookie)) { $this->debug('Remove cookie that is not an array'); continue; } if ((isset($cookie['expires'])) && (!empty($cookie['expires']))) { if (strtotime($cookie['expires']) > time()) { $this->cookies[] = $cookie; } else { $this->debug('Remove expired cookie ' . $cookie['name']); } } else { $this->cookies[] = $cookie; } } $this->debug('checkCookie: ' . sizeof($this->cookies) . ' cookies left in array'); return true; }
php
{ "resource": "" }
q6427
Route.addRoute
train
private function addRoute($method, $uri, $controller, $action) { // Prefix route uri, concat it and clear if (strlen($this->prefixUri) > 0) { $uri = $this->prefixUri . $uri; $this->prefixUri = ''; } // Compatible: has no namespace if (strrpos($controller, '\\', 1) === false) { $controller = 'App\\Controllers\\' . $controller; } $items = $uri ? explode('/', ltrim($uri, '/')) : []; $this->routes[] = [ 'method' => $method, 'count' => count($items), 'controller' => $controller, 'action' => $action, 'params' => $items, ]; }
php
{ "resource": "" }
q6428
Route.findWebSocketRoute
train
public function findWebSocketRoute() { $pathinfo = !empty($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] != '/' ? $_SERVER['PATH_INFO'] : '/index'; foreach ($this->routes as $value) { if ($value['method'] == 'WEBSOCKET') { $route_uri = '/' . implode('/', $value['params']); if ($pathinfo === $route_uri) { return $value['controller']; } } } return ''; }
php
{ "resource": "" }
q6429
Route.head
train
public function head(string $uri, string $controller, string $action) { $this->addRoute('HEAD', $uri, $controller, $action); }
php
{ "resource": "" }
q6430
Route.websocket
train
public function websocket(string $uri, string $controller) { $this->addRoute('WEBSOCKET', $uri, $controller, null); }
php
{ "resource": "" }
q6431
Route.all
train
public function all(string $uri, string $controller, string $action) { $this->addRoute('ALL', $uri, $controller, $action); }
php
{ "resource": "" }
q6432
Email.from
train
public function from($email, $name = '') { $value = $this->parseMail($this->filtreEmail($email), $this->filtreName($name)); return $this->withHeader('from', $value); }
php
{ "resource": "" }
q6433
Email.send
train
public function send() { $to = $this->getHeaderLine('to'); $subject = $this->subject; $message = $this->message; return mail($to, $subject, $message, $this->parseHeaders()); }
php
{ "resource": "" }
q6434
AbstractCallback.updatePaymentTransaction
train
protected function updatePaymentTransaction(PaymentTransaction $paymentTransaction, CallbackResponse $callbackResponse) { $paymentTransaction->setStatus($callbackResponse->getStatus()); $paymentTransaction->getPayment()->setPaynetId($callbackResponse->getPaymentPaynetId()); if ($callbackResponse->isError() || $callbackResponse->isDeclined()) { $paymentTransaction->addError($callbackResponse->getError()); } }
php
{ "resource": "" }
q6435
AbstractCallback.validateSignature
train
protected function validateSignature(PaymentTransaction $paymentTransaction, CallbackResponse $callbackResponse) { // This is SHA-1 checksum of the concatenation // status + orderid + client_orderid + merchant-control. $expectedControlCode = sha1 ( $callbackResponse->getStatus() . $callbackResponse->getPaymentPaynetId() . $callbackResponse->getPaymentClientId() . $paymentTransaction->getQueryConfig()->getSigningKey() ); if($expectedControlCode !== $callbackResponse->getControlCode()) { throw new ValidationException("Actual control code '{$callbackResponse->getControlCode()}' does " . "not equal expected '{$expectedControlCode}'"); } }
php
{ "resource": "" }
q6436
AbstractWidget.fieldsFactory
train
public static function fieldsFactory() { //====================================================================// // Initialize Field Factory Class if (isset(self::$fields)) { return self::$fields; } //====================================================================// // Initialize Class self::$fields = new FieldsFactory(); //====================================================================// // Load Translation File Splash::translator()->load("objects"); return self::$fields; }
php
{ "resource": "" }
q6437
AbstractWidget.blocksFactory
train
public static function blocksFactory() { //====================================================================// // Initialize Field Factory Class if (isset(self::$blocks)) { return self::$blocks; } //====================================================================// // Initialize Class self::$blocks = new BlocksFactory(); return self::$blocks; }
php
{ "resource": "" }
q6438
AbstractWidget.description
train
public function description() { //====================================================================// // Stack Trace Splash::log()->trace(); //====================================================================// // Build & Return Widget Description Array return array( //====================================================================// // General Object definition "type" => $this->getType(), // Widget Type Name "name" => $this->getName(), // Widget Display Neme "description" => $this->getDesc(), // Widget Descritioon "icon" => $this->getIcon(), // Widget Icon "disabled" => $this->getIsDisabled(), // Is This Widget Enabled or Not? //====================================================================// // Widget Default Options "options" => $this->getOptions(), // Widget Default Options Array //====================================================================// // Widget Parameters "parameters" => $this->getParameters(), // Widget Default Options Array ); }
php
{ "resource": "" }
q6439
DefinitionConfiguration.defineAttributes
train
protected function defineAttributes(NodeBuilder $builder) { $builder->arrayNode('attributes') ->useAttributeAsKey('') ->prototype('array') ->children() ->scalarNode('type') ->cannotBeEmpty() ->end() ->scalarNode('getter') ->cannotBeEmpty() ->end() ->scalarNode('setter') ->cannotBeEmpty() ->end() ->booleanNode('processNull') ->defaultFalse() ->end(); }
php
{ "resource": "" }
q6440
DefinitionConfiguration.defineRelationships
train
protected function defineRelationships(NodeBuilder $builder) { $relationships = $builder->arrayNode('relationships') ->useAttributeAsKey('') ->prototype('array') ->children() ->enumNode('type') ->values(['one', 'many']) ->cannotBeEmpty() ->defaultValue('one') ->end() ->scalarNode('getter') ->cannotBeEmpty() ->end() ->booleanNode('dataAllowed') ->defaultFalse() ->end() ->integerNode('dataLimit') ->defaultValue(0) ->end(); $this->defineLinks($relationships); }
php
{ "resource": "" }
q6441
DefinitionConfiguration.defineLinks
train
protected function defineLinks(NodeBuilder $builder) { $builder->arrayNode('links') ->useAttributeAsKey('') ->prototype('array') ->children() ->scalarNode('resource') ->isRequired() ->cannotBeEmpty() ->end() ->arrayNode('parameters') ->prototype('scalar')->end() ->end() ->arrayNode('metadata') ->prototype('scalar')->end() ->end(); }
php
{ "resource": "" }
q6442
SplashRequestParameterFetcher.fetchValue
train
public function fetchValue($data, SplashRequestContext $context) { $key = $data['key']; $compulsory = $data['compulsory']; $default = $data['default'] ?? null; return $context->getParameter($key, $compulsory, $default); }
php
{ "resource": "" }
q6443
NewsResourceController.index
train
public function index(NewsRequest $request) { $view = $this->response->theme->listView(); if ($this->response->typeIs('json')) { $function = camel_case('get-' . $view); return $this->repository ->setPresenter(\Litecms\News\Repositories\Presenter\NewsPresenter::class) ->$function(); } $news = $this->repository->paginate(); return $this->response->title(trans('news::news.names')) ->view('news::news.index', true) ->data(compact('news')) ->output(); }
php
{ "resource": "" }
q6444
NewsResourceController.show
train
public function show(NewsRequest $request, News $news) { if ($news->exists) { $view = 'news::news.show'; } else { $view = 'news::news.new'; } return $this->response->title(trans('app.view') . ' ' . trans('news::news.name')) ->data(compact('news')) ->view($view, true) ->output(); }
php
{ "resource": "" }
q6445
NewsResourceController.edit
train
public function edit(NewsRequest $request, News $news) { return $this->response->title(trans('app.edit') . ' ' . trans('news::news.name')) ->view('news::news.edit', true) ->data(compact('news')) ->output(); }
php
{ "resource": "" }
q6446
NewsResourceController.update
train
public function update(NewsRequest $request, News $news) { try { $attributes = $request->all(); $news->update($attributes); return $this->response->message(trans('messages.success.updated', ['Module' => trans('news::news.name')])) ->code(204) ->status('success') ->url(guard_url('news/news/' . $news->getRouteKey())) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->code(400) ->status('error') ->url(guard_url('news/news/' . $news->getRouteKey())) ->redirect(); } }
php
{ "resource": "" }
q6447
NewsResourceController.destroy
train
public function destroy(NewsRequest $request, News $news) { try { $news->delete(); return $this->response->message(trans('messages.success.deleted', ['Module' => trans('news::news.name')])) ->code(202) ->status('success') ->url(guard_url('news/news/0')) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->code(400) ->status('error') ->url(guard_url('news/news/' . $news->getRouteKey())) ->redirect(); } }
php
{ "resource": "" }
q6448
SplashRouter.purgeExpiredRoutes
train
private function purgeExpiredRoutes() { $expireTag = ''; foreach ($this->routeProviders as $routeProvider) { /* @var $routeProvider UrlProviderInterface */ $expireTag .= $routeProvider->getExpirationTag(); } $value = md5($expireTag); $urlNodesCacheItem = $this->cachePool->getItem('splashExpireTag'); if ($urlNodesCacheItem->isHit() && $urlNodesCacheItem->get() === $value) { return; } $this->purgeUrlsCache(); $urlNodesCacheItem->set($value); $this->cachePool->save($urlNodesCacheItem); }
php
{ "resource": "" }
q6449
SplashRouter.getSplashActionsList
train
public function getSplashActionsList(): array { $urls = array(); foreach ($this->routeProviders as $routeProvider) { /* @var $routeProvider UrlProviderInterface */ $tmpUrlList = $routeProvider->getUrlsList(null); $urls = array_merge($urls, $tmpUrlList); } return $urls; }
php
{ "resource": "" }
q6450
SplashRouter.generateUrlNode
train
private function generateUrlNode($urlsList) { $urlNode = new SplashUrlNode(); foreach ($urlsList as $splashAction) { $urlNode->registerCallback($splashAction); } return $urlNode; }
php
{ "resource": "" }
q6451
ControllerAnalyzer.analyzeController
train
public function analyzeController(string $controllerInstanceName) : array { // Let's analyze the controller and get all the @Action annotations: $urlsList = array(); $controller = $this->container->get($controllerInstanceName); $refClass = new \ReflectionClass($controller); foreach ($refClass->getMethods() as $refMethod) { $title = null; // Now, let's check the "Title" annotation (note: we do not support multiple title annotations for the same method) /** @var Title */ $titleAnnotation = $this->annotationReader->getMethodAnnotation($refMethod, Title::class); if ($titleAnnotation !== null) { $title = $titleAnnotation->getTitle(); } // First, let's check the "Action" annotation $actionAnnotation = $this->annotationReader->getMethodAnnotation($refMethod, Action::class); if ($actionAnnotation !== null) { $methodName = $refMethod->getName(); if ($methodName === 'index') { $url = $controllerInstanceName.'/'; } else { $url = $controllerInstanceName.'/'.$methodName; } $parameters = $this->parameterFetcherRegistry->mapParameters($refMethod); $filters = FilterUtils::getFilters($refMethod, $this->annotationReader); $urlsList[] = new SplashRoute($url, $controllerInstanceName, $refMethod->getName(), $title, $refMethod->getDocComment(), $this->getSupportedHttpMethods($refMethod), $parameters, $filters, $refClass->getFileName()); } // Now, let's check the "URL" annotation (note: we support multiple URL annotations for the same method) $annotations = $this->annotationReader->getMethodAnnotations($refMethod); foreach ($annotations as $annotation) { if (!$annotation instanceof URL) { continue; } /* @var $annotation URL */ $url = $annotation->getUrl(); // Get public properties if they exist in the URL if (preg_match_all('/[^{]*{\$this->([^\/]*)}[^{]*/', $url, $output)) { foreach ($output[1] as $param) { $value = $this->readPrivateProperty($controller, $param); $url = str_replace('{$this->'.$param.'}', $value, $url); } } $url = ltrim($url, '/'); $parameters = $this->parameterFetcherRegistry->mapParameters($refMethod, $url); $filters = FilterUtils::getFilters($refMethod, $this->annotationReader); $urlsList[] = new SplashRoute($url, $controllerInstanceName, $refMethod->getName(), $title, $refMethod->getDocComment(), $this->getSupportedHttpMethods($refMethod), $parameters, $filters, $refClass->getFileName()); } } return $urlsList; }
php
{ "resource": "" }
q6452
CommentPolicy.update
train
public function update(UserPolicy $user, Comment $comment) { if ($user->canDo('news.comment.edit') && $user->isAdmin()) { return true; } return $comment->user_id == user_id() && $comment->user_type == user_type(); }
php
{ "resource": "" }
q6453
CommentPolicy.destroy
train
public function destroy(UserPolicy $user, Comment $comment) { return $comment->user_id == user_id() && $comment->user_type == user_type(); }
php
{ "resource": "" }
q6454
ControllerRegistry.getExpirationTag
train
public function getExpirationTag() : string { // An approximate, quick-to-compute rule that will force renewing the cache if a controller is added are a parameter is fetched. return implode('-/-', $this->controllers).($this->controllerDetector !== null ? $this->controllerDetector->getExpirationTag() : ''); }
php
{ "resource": "" }
q6455
ParameterFetcherRegistry.toArguments
train
public function toArguments(SplashRequestContext $context, array $parametersMap) : array { $arguments = []; foreach ($parametersMap as $parameter) { $fetcherid = $parameter['fetcherId']; $data = $parameter['data']; $arguments[] = $this->parameterFetchers[$fetcherid]->fetchValue($data, $context); } return $arguments; }
php
{ "resource": "" }
q6456
CategoryPolicy.destroy
train
public function destroy(UserPolicy $user, Category $category) { return $category->user_id == user_id() && $category->user_type == user_type(); }
php
{ "resource": "" }
q6457
NewsPolicy.view
train
public function view(UserPolicy $user, News $news) { if ($user->canDo('news.news.view') && $user->isAdmin()) { return true; } return $news->user_id == user_id() && $news->user_type == user_type(); }
php
{ "resource": "" }
q6458
NewsPolicy.destroy
train
public function destroy(UserPolicy $user, News $news) { return $news->user_id == user_id() && $news->user_type == user_type(); }
php
{ "resource": "" }
q6459
CommentResourceController.edit
train
public function edit(CommentRequest $request, Comment $comment) { return $this->response->title(trans('app.edit') . ' ' . trans('news::comment.name')) ->view('news::comment.edit', true) ->data(compact('comment')) ->output(); }
php
{ "resource": "" }
q6460
TagPolicy.view
train
public function view(UserPolicy $user, Tag $tag) { if ($user->canDo('news.tag.view') && $user->isAdmin()) { return true; } return $tag->user_id == user_id() && $tag->user_type == user_type(); }
php
{ "resource": "" }
q6461
TagPolicy.destroy
train
public function destroy(UserPolicy $user, Tag $tag) { return $tag->user_id == user_id() && $tag->user_type == user_type(); }
php
{ "resource": "" }
q6462
TagResourceController.index
train
public function index(TagRequest $request) { $view = $this->response->theme->listView(); if ($this->response->typeIs('json')) { $function = camel_case('get-' . $view); return $this->repository ->setPresenter(\Litecms\News\Repositories\Presenter\TagPresenter::class) ->$function(); } $tags = $this->repository->paginate(); return $this->response->title(trans('news::tag.names')) ->view('news::tag.index', true) ->data(compact('tags')) ->output(); }
php
{ "resource": "" }
q6463
TagResourceController.show
train
public function show(TagRequest $request, Tag $tag) { if ($tag->exists) { $view = 'news::tag.show'; } else { $view = 'news::tag.new'; } return $this->response->title(trans('app.view') . ' ' . trans('news::tag.name')) ->data(compact('tag')) ->view($view, true) ->output(); }
php
{ "resource": "" }
q6464
TagResourceController.delete
train
public function delete(TagRequest $request, $type) { try { $ids = hashids_decode($request->input('ids')); if ($type == 'purge') { $this->repository->purge($ids); } else { $this->repository->delete($ids); } return $this->response->message(trans('messages.success.deleted', ['Module' => trans('news::tag.name')])) ->status("success") ->code(202) ->url(guard_url('news/tag')) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->status("error") ->code(400) ->url(guard_url('/news/tag')) ->redirect(); } }
php
{ "resource": "" }
q6465
SplashUrlNode.walkArray
train
private function walkArray(array $urlParts, ServerRequestInterface $request, array $parameters, $closestWildcardRoute = null) { $httpMethod = $request->getMethod(); if (isset($this->wildcardCallbacks[$httpMethod])) { $closestWildcardRoute = $this->wildcardCallbacks[$httpMethod]; $closestWildcardRoute->setFilledParameters($parameters); } elseif (isset($this->wildcardCallbacks[''])) { $closestWildcardRoute = $this->wildcardCallbacks['']; $closestWildcardRoute->setFilledParameters($parameters); } if (!empty($urlParts)) { $key = array_shift($urlParts); if (isset($this->children[$key])) { return $this->children[$key]->walkArray($urlParts, $request, $parameters, $closestWildcardRoute); } foreach ($this->parameterizedChildren as $varName => $splashUrlNode) { if (isset($parameters[$varName])) { throw new SplashException("An error occured while looking at the list URL managed in Splash. In a @URL annotation, the parameter '{$parameters[$varName]}' appears twice. That should never happen"); } $newParams = $parameters; $newParams[$varName] = $key; $result = $this->parameterizedChildren[$varName]->walkArray($urlParts, $request, $newParams, $closestWildcardRoute); if ($result !== null) { return $result; } } // If we arrive here, there was no parametrized URL matching our objective return $closestWildcardRoute; } else { if (isset($this->callbacks[$httpMethod])) { $route = $this->callbacks[$httpMethod]; $route->setFilledParameters($parameters); return $route; } elseif (isset($this->callbacks[''])) { $route = $this->callbacks['']; $route->setFilledParameters($parameters); return $route; } else { return $closestWildcardRoute; } } }
php
{ "resource": "" }
q6466
CroppableImageField.CroppableImageForm
train
public function CroppableImageForm() { $image = $this->getCroppableImageObject(); $action = FormAction::create('doSaveCroppableImage', _t('CroppableImageable.SAVE', 'Save'))->setUseButtonTag('true'); if (!$this->isFrontend) { $action->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'); } $image = null; if ($CroppableImageID = (int) $this->request->getVar('SaltedCroppableImageID')) { $image = SaltedCroppableImage::get()->byID($CroppableImageID); } $image = $image ? $image : singleton('SaltedCroppableImage'); // $image->setAllowedTypes($this->getAllowedTypes()); $fields = $image->getCMSFields(); $title = $image ? _t('CroppableImageable.EDITIMAGE', 'Edit Image') : _t('CroppableImageable.ADDIMAGE', 'Add Image'); $fields->insertBefore(HeaderField::create('CroppableImageHeader', $title), _t('CroppableImageable.TITLE', 'Title')); $actions = FieldList::create($action); $form = Form::create($this, 'CroppableImageForm', $fields, $actions); if ($image) { $form->loadDataFrom($image); if (!empty($this->folderName)) { $fields->fieldByName('Root.Main.Original')->setFolderName($this->folderName); } $fields->push(HiddenField::create('CropperRatio')->setValue($this->Ratio)); $fields->push(HiddenField::create('ContainerX')->setValue($image->ContainerX)); $fields->push(HiddenField::create('ContainerX')->setValue($image->ContainerX)); $fields->push(HiddenField::create('ContainerY')->setValue($image->ContainerY)); $fields->push(HiddenField::create('ContainerWidth')->setValue($image->ContainerWidth)); $fields->push(HiddenField::create('ContainerHeight')->setValue($image->ContainerHeight)); $fields->push(HiddenField::create('CropperX')->setValue($image->CropperX)); $fields->push(HiddenField::create('CropperY')->setValue($image->CropperY)); $fields->push(HiddenField::create('CropperWidth')->setValue($image->CropperWidth)); $fields->push(HiddenField::create('CropperHeight')->setValue($image->CropperHeight)); } $this->owner->extend('updateLinkForm', $form); return $form; }
php
{ "resource": "" }
q6467
ScriptEngineManager.getConfig
train
protected function getConfig($name) { if (empty($name)) { throw new InvalidArgumentException("Script Engine 'name' can not be empty."); } $engines = $this->app['config']['df.script']; return array_get($engines, $name, []); }
php
{ "resource": "" }
q6468
ScriptEngineManager.makeEngine
train
public function makeEngine($type, array $script_config = []) { if (!empty($disable = config('df.scripting.disable'))) { switch (strtolower($disable)) { case 'all': throw new ServiceUnavailableException("All scripting is disabled for this instance."); break; default: if (!empty($type) && (false !== stripos($disable, $type))) { throw new ServiceUnavailableException("Scripting with $type is disabled for this instance."); } break; } } $config = $this->getConfig($type); // Next we will check to see if a type extension has been registered for a engine type // and will call the factory Closure if so, which allows us to have a more generic // resolver for the engine types themselves which applies to all scripting. if (isset($this->types[$type])) { return $this->types[$type]->make(array_merge($config, $script_config)); } throw new InvalidArgumentException("Unsupported script engine type '$type'."); }
php
{ "resource": "" }
q6469
Php.stripPhpTag
train
protected static function stripPhpTag($script) { $script = trim($script); $tagOpen = strtolower(substr($script, 0, 5)); $tagClose = substr($script, strlen($script)-2); if('<?php' === $tagOpen){ $script = substr($script, 5); } if('?>' === $tagClose){ $script = substr($script, 0, (strlen($script)-2)); } return $script; }
php
{ "resource": "" }
q6470
AttributeTypeAvMetaQuery.filterByAttributeAvId
train
public function filterByAttributeAvId($attributeAvId = null, $comparison = null) { if (is_array($attributeAvId)) { $useMinMax = false; if (isset($attributeAvId['min'])) { $this->addUsingAlias(AttributeTypeAvMetaTableMap::ATTRIBUTE_AV_ID, $attributeAvId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($attributeAvId['max'])) { $this->addUsingAlias(AttributeTypeAvMetaTableMap::ATTRIBUTE_AV_ID, $attributeAvId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AttributeTypeAvMetaTableMap::ATTRIBUTE_AV_ID, $attributeAvId, $comparison); }
php
{ "resource": "" }
q6471
AttributeTypeAvMetaQuery.filterByAttributeAttributeTypeId
train
public function filterByAttributeAttributeTypeId($attributeAttributeTypeId = null, $comparison = null) { if (is_array($attributeAttributeTypeId)) { $useMinMax = false; if (isset($attributeAttributeTypeId['min'])) { $this->addUsingAlias(AttributeTypeAvMetaTableMap::ATTRIBUTE_ATTRIBUTE_TYPE_ID, $attributeAttributeTypeId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($attributeAttributeTypeId['max'])) { $this->addUsingAlias(AttributeTypeAvMetaTableMap::ATTRIBUTE_ATTRIBUTE_TYPE_ID, $attributeAttributeTypeId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(AttributeTypeAvMetaTableMap::ATTRIBUTE_ATTRIBUTE_TYPE_ID, $attributeAttributeTypeId, $comparison); }
php
{ "resource": "" }
q6472
AttributeTypeAvMetaQuery.filterByAttributeAv
train
public function filterByAttributeAv($attributeAv, $comparison = null) { if ($attributeAv instanceof \Thelia\Model\AttributeAv) { return $this ->addUsingAlias(AttributeTypeAvMetaTableMap::ATTRIBUTE_AV_ID, $attributeAv->getId(), $comparison); } elseif ($attributeAv instanceof ObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(AttributeTypeAvMetaTableMap::ATTRIBUTE_AV_ID, $attributeAv->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByAttributeAv() only accepts arguments of type \Thelia\Model\AttributeAv or Collection'); } }
php
{ "resource": "" }
q6473
AttributeTypeAvMetaQuery.useAttributeAvQuery
train
public function useAttributeAvQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinAttributeAv($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'AttributeAv', '\Thelia\Model\AttributeAvQuery'); }
php
{ "resource": "" }
q6474
AttributeTypeAvMetaQuery.useAttributeAttributeTypeQuery
train
public function useAttributeAttributeTypeQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinAttributeAttributeType($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'AttributeAttributeType', '\AttributeType\Model\AttributeAttributeTypeQuery'); }
php
{ "resource": "" }
q6475
RequestReader.getBody
train
public function getBody(RequestInterface $request, $readerType = null) { $data = (string) $request->getBody(); $payload = Payload::create($data, $request->getHeader('Content-Type')) ->setRwType($readerType); return $this->processor->parse($payload); }
php
{ "resource": "" }
q6476
ImgixDataLoader.find
train
public function find($path) { $imgix = $this->serializer->deserialize($path); if ($imgix) { return file_get_contents($this->source . $imgix); } throw new NotLoadableException; }
php
{ "resource": "" }
q6477
Smtp.Smtp_Ok
train
private function Smtp_Ok() { $_res = str_replace("\r\n", '', fgets($this->Smtp_Socket, 512)); if ( ! preg_match('/^[23]/', $_res)) { fputs($this->Smtp_Socket, "QUIT\r\n"); fgets($this->Smtp_Socket, 512); return FALSE; } return TRUE; }
php
{ "resource": "" }
q6478
Smtp.Run_Cmd
train
private function Run_Cmd($_cmd, $_args = '') { if ( $_args != '' ) { if ( $_cmd == '' ) $_cmd = $_args; else $_cmd = $_cmd." ".$_args; //$_cmd == ''?$_cmd = $_args:$_cmd." ".$_args; } fputs($this->Smtp_Socket, $_cmd."\r\n"); return $this->Smtp_Ok(); //return the response code }
php
{ "resource": "" }
q6479
Smtp.Strip_Comment
train
private function Strip_Comment($_address) { $_pattern = "/\([^()]*\)/"; while ( preg_match($_pattern, $_address) ) $_address = preg_replace($_pattern, '', $_address); return $_address; }
php
{ "resource": "" }
q6480
MenuItemContainerTrait.getMenuItems
train
public function getMenuItems(): array { usort($this->menuItems, function ($a, $b) { return $a->getOrder() > $b->getOrder(); }); return $this->menuItems; }
php
{ "resource": "" }
q6481
MenuItemContainerTrait.removeMenuItem
train
public function removeMenuItem(MenuItemInterface $item): void { $key = array_search($item, $this->menuItems, true); if ($key !== false) { unset($this->menuItems[$key]); } }
php
{ "resource": "" }
q6482
LanguageList.getOne
train
public function getOne($languageCode, $locale = 'en') { $result = $this->has($languageCode, $locale); if (!$result) { throw new LanguageNotFoundException($languageCode); } return $result; }
php
{ "resource": "" }
q6483
LanguageList.loadData
train
protected function loadData($locale, $format) { if (!isset($this->dataCache[$locale][$format])) { $file = sprintf('%s/%s/language.'.$format, $this->dataDir, $locale); if (!is_file($file)) { throw new \RuntimeException(sprintf('Unable to load the language data file "%s"', $file)); } $this->dataCache[$locale][$format] = ($format == 'php') ? require $file : file_get_contents($file); } return $this->sortData($locale, $this->dataCache[$locale][$format]); }
php
{ "resource": "" }
q6484
Searchable.scopeSearch
train
public function scopeSearch(Builder $query, ?string $keyword, ?array $columns = null): Builder { return $this->setupWildcardQueryFilter($query, $keyword ?? '', $columns ?? $this->getSearchableColumns()); }
php
{ "resource": "" }
q6485
HasMetadata.getMetadata
train
public function getMetadata($key = null) { if (is_null($this->metadataCache)) { $this->metadataCache = json_decode($this->metadata, true); } if (is_null($key)) { return $this->metadataCache; } if (isset($this->metadataCache[$key])) { return $this->metadataCache[$key]; } return null; }
php
{ "resource": "" }
q6486
HasMetadata.setMetadata
train
public function setMetadata($key, $value) { if (is_null($this->metadataCache)) { $this->metadataCache = []; } $this->metadataCache[$key] = $value; }
php
{ "resource": "" }
q6487
ResourceBuilder.isArrayResourceData
train
private function isArrayResourceData($data) { if (!is_array($data) || empty($data)) { return false; } foreach ($data as $datum) { if (!$this->isResourceData($datum)) { return false; } } return true; }
php
{ "resource": "" }
q6488
RestClient.request
train
public function request($method, $url, array $data = []) { return $this->request->send($this->baseUrl.'/'.$url, $method, $data); }
php
{ "resource": "" }
q6489
Document.set
train
public function set($name, $data = []) { if (!is_array($name) || (isset($name[0]) && is_string($name[0]))) { $this->setAt($name, $data); return $this; } $data = $name; if (!is_array($data)) { throw new ORMException('Invalid bulk data for a document.'); } foreach ($data as $name => $value) { $this->setAt($name, $value); } return $this; }
php
{ "resource": "" }
q6490
Document.hierarchy
train
public function hierarchy($prefix = '', &$ignore = [], $index = false) { $hash = spl_object_hash($this); if (isset($ignore[$hash])) { return false; } $ignore[$hash] = true; $tree = array_fill_keys($this->schema()->relations(), true); $result = []; $habtm = []; foreach ($tree as $field => $value) { $rel = $this->schema()->relation($field); if ($rel->type() === 'hasManyThrough') { $habtm[$field] = $rel; continue; } if (!isset($this->{$field})) { continue; } $entity = $this->__get($field); // Too Many Magic Kill The Magic. if ($entity) { $path = $prefix ? $prefix . '.' . $field : $field; if ($children = $entity->hierarchy($path, $ignore, true)) { $result += $children; } elseif ($children !== false) { $result[$path] = $path; } } } foreach ($habtm as $field => $rel) { $using = $rel->through() . '.' . $rel->using(); $path = $prefix ? $prefix . '.' . $using : $using; foreach ($result as $key) { if (strpos($key, $path) === 0) { $path = $prefix ? $prefix . '.' . $field : $field; $result[$path] = $path; } } } return $index ? $result : array_values($result); }
php
{ "resource": "" }
q6491
BaseEngineAdapter.loadScript
train
public static function loadScript($name, $path = null, $returnContents = true) { // Already read, return script if (null !== ($script = array_get(static::$libraries, $name))) { return $returnContents ? file_get_contents($script) : $script; } $script = ltrim($script, ' /'); // Spin through paths and look for the script foreach (static::$libraryPaths as $libPath) { $check = $libPath . '/' . $script; if (is_file($check) && is_readable($check)) { array_set(static::$libraries, $name, $check); return $returnContents ? file_get_contents($check) : $check; } } if ($path) { if (is_file($path) && is_readable($path)) { array_set(static::$libraries, $name, $path); return $returnContents ? file_get_contents($path) : $path; } } return false; }
php
{ "resource": "" }
q6492
BaseEngineAdapter.getLibrary
train
protected static function getLibrary($id, $file = null) { if (null !== $file || array_key_exists($id, static::$libraries)) { $file = $file ?: static::$libraries[$id]; // Find the library foreach (static::$libraryPaths as $name => $path) { $filePath = $path . DIRECTORY_SEPARATOR . $file; if (file_exists($filePath) && is_readable($filePath)) { return file_get_contents($filePath, 'r'); } } } throw new \InvalidArgumentException('The library id "' . $id . '" could not be located.'); }
php
{ "resource": "" }
q6493
BaseEngineAdapter.makeJsonSafe
train
protected function makeJsonSafe($data, $base64 = true) { if (is_array($data)) { foreach ($data as $key => $value) { $data[$key] = $this->makeJsonSafe($value, $base64); } } if (!$this->isJsonEncodable($data)) { if (true === $base64) { return 'base64:' . base64_encode($data); } else { return '--non-parsable-data--'; } } return $data; }
php
{ "resource": "" }
q6494
BaseEngineAdapter.isJsonEncodable
train
protected function isJsonEncodable($data) { if (!is_array($data)) { $data = [$data]; } $json = json_encode($data, JSON_UNESCAPED_SLASHES); if ($json === false) { return false; } return true; }
php
{ "resource": "" }
q6495
MandrillTransport._exec
train
private function _exec($params) { $params['key'] = $this->_config['api_key']; $params = json_encode($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, 'Mandrill-PHP/1.0.52'); curl_setopt($ch, CURLOPT_POST, true); if (!ini_get('safe_mode') && !ini_get('open_basedir')){ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); } curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 600); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send.json'); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_VERBOSE, false); $response_body = curl_exec($ch); if(curl_error($ch)) { throw new Exception("API call to messages/send failed: " . curl_error($ch)); } $result = json_decode($response_body, true); if($result === null) throw new Exception('We were unable to decode the JSON response from the Mandrill API: ' . $response_body); return $result; }
php
{ "resource": "" }
q6496
Role.saving
train
public function saving(Eloquent $model): void { $keyword = Keyword::make($model->getAttribute('name')); if ($keyword->searchIn(['guest']) !== false) { throw new InvalidArgumentException("Role [{$keyword->getValue()}] is not allowed to be used!"); } }
php
{ "resource": "" }
q6497
Role.isRestoringModel
train
protected function isRestoringModel(Eloquent $model): bool { if (! $model->isSoftDeleting()) { return false; } $deleted = $model->getDeletedAtColumn(); return \is_null($model->getAttribute($deleted)) && ! \is_null($model->getOriginal($deleted)); }
php
{ "resource": "" }
q6498
TransitServiceProvider.register
train
public function register() { $this->registerUploadPath(); $this->registerAssetPath(); $this->registerUploadService(); $this->registerDownloadService(); $this->registerCommands(); }
php
{ "resource": "" }
q6499
ValidatingObserver.validate
train
protected function validate(Model $model) { $attributes = $model->getAttributes(); $messages = isset($model->validationMessages) ? $model->validationMessages : []; $validator = $this->factory->make($attributes, $model->rules, $messages); if ($validator->fails()) { throw new ValidationException($validator->getMessageBag()); } if (method_exists($model, 'validate')) { $model->validate(); } }
php
{ "resource": "" }