sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function handleResource($resource) { if(!self::$_resourceLoader) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Unable to handle resources - resource plugin loader not set'); } try { while(is_resource($resource)) { $resclass = self::getResourceParser($resource); if(!$resclass) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Can not serialize resource type: '. get_resource_type($resource)); } $parser = new $resclass(); if(is_callable(array($parser, 'parse'))) { $resource = $parser->parse($resource); } else { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception("Could not call parse() method on class $resclass"); } } return $resource; } catch(Zend_Amf_Exception $e) { throw new Zend_Amf_Exception($e->getMessage(), $e->getCode(), $e); } catch(Exception $e) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Can not serialize resource type: '. get_resource_type($resource), 0, $e); } }
Convert resource to a serializable object @param resource $resource @return mixed
entailment
protected function _create(array $data, $id = null, array $parameters = []) { return parent::_create($data, $this->type(), $id, $parameters); }
Overrides the parent class _create method to omit the type in parameters. @see Query::_create for details. @param mixed $id @return Result|Model[]
entailment
protected function _fullModelClass() { $baseClassName = $this->modelClassName(); $classNamePattern = $this->modelClassNamePattern(); if ($classNamePattern && strpos($classNamePattern, '{type}') !== false) { $fullClassName = str_replace("{type}", $baseClassName, $classNamePattern); } elseif ($classNamePattern) { $fullClassName = "{$classNamePattern}{$baseClassName}"; } else { $fullClassName = "\\{$baseClassName}"; } return $fullClassName; }
Creates the full model class name It uses the query::modelClassNamePattern and typequery::modelClassName methods to create the full classname. @return string
entailment
protected function _makeResult(array $result) { return Result::make($result, $this->getClient())->setModelClass($this->_fullModelClass()); }
Overrides the parent class _makeResult method to pass the correct model class name. @see Query::_makeResult for details. @param array $result @return Result|Model[]
entailment
public function setType($type) { if (!is_string($type) && (null !== $type)) { require_once 'Zend/Server/Reflection/Exception.php'; throw new Zend_Server_Reflection_Exception('Invalid parameter type'); } $this->_type = $type; }
Set parameter type @param string|null $type @return void
entailment
public function setDescription($description) { if (!is_string($description) && (null !== $description)) { require_once 'Zend/Server/Reflection/Exception.php'; throw new Zend_Server_Reflection_Exception('Invalid parameter description'); } $this->_description = $description; }
Set parameter description @param string|null $description @return void
entailment
public function readTypeMarker($typeMarker = null) { if ($typeMarker === null) { $typeMarker = $this->_stream->readByte(); } switch($typeMarker) { // number case Zend_Amf_Constants::AMF0_NUMBER: return $this->_stream->readDouble(); // boolean case Zend_Amf_Constants::AMF0_BOOLEAN: return (boolean) $this->_stream->readByte(); // string case Zend_Amf_Constants::AMF0_STRING: return $this->_stream->readUTF(); // object case Zend_Amf_Constants::AMF0_OBJECT: return $this->readObject(); // null case Zend_Amf_Constants::AMF0_NULL: return null; // undefined case Zend_Amf_Constants::AMF0_UNDEFINED: return null; // Circular references are returned here case Zend_Amf_Constants::AMF0_REFERENCE: return $this->readReference(); // mixed array with numeric and string keys case Zend_Amf_Constants::AMF0_MIXEDARRAY: return $this->readMixedArray(); // array case Zend_Amf_Constants::AMF0_ARRAY: return $this->readArray(); // date case Zend_Amf_Constants::AMF0_DATE: return $this->readDate(); // longString strlen(string) > 2^16 case Zend_Amf_Constants::AMF0_LONGSTRING: return $this->_stream->readLongUTF(); //internal AS object, not supported case Zend_Amf_Constants::AMF0_UNSUPPORTED: return null; // XML case Zend_Amf_Constants::AMF0_XML: return $this->readXmlString(); // typed object ie Custom Class case Zend_Amf_Constants::AMF0_TYPEDOBJECT: return $this->readTypedObject(); //AMF3-specific case Zend_Amf_Constants::AMF0_AMF3: return $this->readAmf3TypeMarker(); default: require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Unsupported marker type: ' . $typeMarker); } }
Read AMF markers and dispatch for deserialization Checks for AMF marker types and calls the appropriate methods for deserializing those marker types. Markers are the data type of the following value. @param integer $typeMarker @return mixed whatever the data type is of the marker in php @throws Zend_Amf_Exception for invalid type
entailment
public function readObject($object = null) { if ($object === null) { $object = array(); } while (true) { $key = $this->_stream->readUTF(); $typeMarker = $this->_stream->readByte(); if ($typeMarker != Zend_Amf_Constants::AMF0_OBJECTTERM ){ //Recursivly call readTypeMarker to get the types of properties in the object $object[$key] = $this->readTypeMarker($typeMarker); } else { //encountered AMF object terminator break; } } $this->_reference[] = $object; return (object) $object; }
Read AMF objects and convert to PHP objects Read the name value pair objects form the php message and convert them to a php object class. Called when the marker type is 3. @param array|null $object @return object
entailment
public function readReference() { $key = $this->_stream->readInt(); if (!array_key_exists($key, $this->_reference)) { require_once 'Zend/Amf/Exception.php'; throw new Zend_Amf_Exception('Invalid reference key: '. $key); } return $this->_reference[$key]; }
Read reference objects Used to gain access to the private array of reference objects. Called when marker type is 7. @return object @throws Zend_Amf_Exception for invalid reference keys
entailment
public function readDate() { // get the unix time stamp. Not sure why ActionScript does not use // milliseconds $timestamp = floor($this->_stream->readDouble() / 1000); // The timezone offset is never returned to the server; it is always 0, // so read and ignore. $offset = $this->_stream->readInt(); require_once 'Zend/Date.php'; $date = new Zend_Date($timestamp); return $date; }
Convert AS Date to Zend_Date @return Zend_Date
entailment
public function readTypedObject() { require_once 'Zend/Amf/Parse/TypeLoader.php'; // get the remote class name $className = $this->_stream->readUTF(); $loader = Zend_Amf_Parse_TypeLoader::loadType($className); $returnObject = new $loader(); $properties = get_object_vars($this->readObject()); foreach($properties as $key=>$value) { if($key) { $returnObject->$key = $value; } } if($returnObject instanceof Zend_Amf_Value_Messaging_ArrayCollection) { $returnObject = get_object_vars($returnObject); } return $returnObject; }
Read Class that is to be mapped to a server class. Commonly used for Value Objects on the server @todo implement Typed Class mapping @return object|array @throws Zend_Amf_Exception if unable to load type
entailment
public function readAmf3TypeMarker() { require_once 'Zend/Amf/Parse/Amf3/Deserializer.php'; $deserializer = new Zend_Amf_Parse_Amf3_Deserializer($this->_stream); $this->_objectEncoding = Zend_Amf_Constants::AMF3_OBJECT_ENCODING; return $deserializer->readTypeMarker(); }
AMF3 data type encountered load AMF3 Deserializer to handle type markers. @return string
entailment
public function toArray() { return array( 'type' => $this->getType(), 'name' => $this->getName(), 'optional' => $this->isOptional(), 'defaultValue' => $this->getDefaultValue(), 'description' => $this->getDescription(), ); }
Cast to array @return array
entailment
public function run() { $this->registerClientScript(); $this->options['data-plugin-name'] = $this->_pluginName; $this->options['data-plugin-options'] = $this->_hashOptions; Html::addCssClass($this->options, 'fullcalendar'); echo '<div id="container_' . $this->options['id'] . '">'; echo '<div class="fc-loading" style="display: none;">' . $this->loading . '</div>'; echo Html::tag('div', '', $this->options); echo '</div>'; }
Runs the widget.
entailment
public function registerClientScript() { $options = $this->getClientOptions(); $this->_hashOptions = $this->_pluginName . '_' . hash('crc32', serialize($options)); $id = $this->options['id']; $view = $this->getView(); $view->registerJs("var {$this->_hashOptions} = {$options};\nvar calendar_{$this->options['id']};", $view::POS_HEAD); $js = "calendar_{$this->options['id']} = jQuery(\"#{$id}\").fullCalendar({$this->_hashOptions});"; $asset = FullCalendarAsset::register($view); if (isset($this->config['lang'])) { $asset->language = $this->config['lang']; } if ($this->googleCalendar) { $asset->googleCalendar = $this->googleCalendar; } $view->registerJs($js); }
Registers the needed JavaScript.
entailment
public static function make($handler) { //No handler specified if (!$handler) { return new BoxGuzzleHttpClient(); } //Custom Implemenation, maybe. if ($handler instanceof BoxHttpClientInterface) { return $handler; } //Handler is a custom configured Guzzle Client if ($handler instanceof Guzzle) { return new BoxGuzzleHttpClient($handler); } //Invalid handler throw new InvalidArgumentException('The http client handler must be an instance of GuzzleHttp\Client or an instance of Kunnu\Box\Http\Clients\BoxHttpClientInterface.'); }
Make HTTP Client @param BoxHttpClientInterface|GuzzleHttp\Client|null $handler @return BoxHttpClientInterface
entailment
private function instantiateParameters(Command $command) { return array_map(function(\ReflectionParameter $param) { return $this->container->get($param->getType()->getName()); }, (new ReflectionClass(get_class($command)))->getMethod('execute')->getParameters()); }
instantiate the parameters for the command's execution method using the constructor injected container. @param Command $command @return array @throws \ReflectionException
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('uecode_api_key'); $rootNode ->children() ->scalarNode('delivery') ->defaultValue('query') ->validate() ->ifNotInArray(array('query', 'header')) ->thenInvalid('Unknown authentication delivery type "%s".') ->end() ->end() ->scalarNode('parameter_name') ->defaultValue('api_key') ->end() ->end() ; return $treeBuilder; }
{@inheritDoc}
entailment
public function getUrl() { if ($this->url === null) { switch ($this->dataType) { case 'json': $this->url = $this->urlJson; break; case 'xml': $this->url = $this->urlXml; break; default: throw new InvalidConfigException('“dataType”配置错误!'); } } return $this->url; }
获取请求地址 @return string @throws InvalidConfigException
entailment
public function offsetGet($offset) { return Model::makeOfType($this->result['hits']['hits'][$offset], $this->modelClass, $this->esClient); }
Gets the document object in the $offset @param integer $offset @return Model
entailment
public function fetch($path) { $result = $this->result; $keys = explode(".", $path); foreach ($keys as $key) { if (!array_key_exists($key, $result)) { return null; } $result = $result[$key]; } return $result; }
Gets specific value from within the result set using dot notation The path should be absolution from the beginning, and include the normal elastic search structure depending on the query type @param string $path
entailment
public function transformImage ($asset = null, $transforms = null, $defaultOptions = []) { if ( !$asset ) { return null; } $pathsModel = new ImgixModel($asset, $transforms, $defaultOptions); return $pathsModel; }
@param null $asset @param null $transforms @param array $defaultOptions @return null|ImgixModel
entailment
public function purge (Asset $asset) { $url = $this->getImgixUrl($asset); Craft::trace( Craft::t( 'imgix', 'Purging asset #{id}: {url}', [ 'id' => $asset->id, 'url' => $url ] ), 'imgix'); return $this->purgeUrl($url); }
@param Asset $asset @return bool
entailment
public function purgeUrl ($url = null) { $apiKey = $this->settings->apiKey; Craft::trace( Craft::t( 'imgix', 'Purging asset: {url}', [ 'url' => $url ] ), 'imgix'); try { $client = Craft::createGuzzleClient([ 'timeout' => 30, 'connect_timeout' => 30 ]); $response = $client->post(self::IMGIX_PURGE_ENDPOINT, [ 'auth' => [ $apiKey, '' ], 'form_params' => [ 'url' => $url, ] ]); Craft::trace( Craft::t( 'imgix', 'Purged asset: {url} - Status code {statusCode}', [ 'url' => $url, 'statusCode' => $response->getStatusCode() ] ), 'imgix'); return $response->getStatusCode() >= 200 && $response->getStatusCode() < 400; } catch (RequestException $e) { Craft::error( Craft::t( 'imgix', 'Failed to purge {url}: {statusCode} {error}', [ 'url' => $url, 'error' => $e->getMessage(), 'statusCode' => $e->getResponse()->getStatusCode() ] ), 'imgix' ); return false; } }
@param null $url @return bool
entailment
public function getImgixUrl (Asset $asset) { $url = null; $domains = $this->settings->imgixDomains; $volume = $asset->getVolume(); $assetUrl = AssetsHelper::generateUrl($volume, $asset); $assetUri = parse_url($assetUrl, PHP_URL_PATH); if ( isset($domains[ $volume->handle ]) ) { $builder = new UrlBuilder($domains[ $volume->handle ]); $builder->setUseHttps(true); if ($token = Imgix::$plugin->getSettings()->imgixSignedToken) $builder->setSignKey($token); $url = UrlHelper::stripQueryString($builder->createURL($assetUri)); } return $url; }
@param Asset $asset @return null|string
entailment
public function setParent(Zend_Server_Reflection_Node $node, $new = false) { $this->_parent = $node; if ($new) { $node->attachChild($this); return; } }
Set parent node @param Zend_Server_Reflection_Node $node @param boolean $new Whether or not the child node is newly created and should always be attached @return void
entailment
public function attachChild(Zend_Server_Reflection_Node $node) { $this->_children[] = $node; if ($node->getParent() !== $this) { $node->setParent($this); } }
Attach a child node @param Zend_Server_Reflection_Node $node @return void
entailment
public function getEndPoints() { $endPoints = array(); if (!$this->hasChildren()) { return $endPoints; } foreach ($this->_children as $child) { $value = $child->getValue(); if (null === $value) { $endPoints[] = $this; } elseif ((null !== $value) && $child->hasChildren()) { $childEndPoints = $child->getEndPoints(); if (!empty($childEndPoints)) { $endPoints = array_merge($endPoints, $childEndPoints); } } elseif ((null !== $value) && !$child->hasChildren()) { $endPoints[] = $child; } } return $endPoints; }
Retrieve the bottommost nodes of this node's tree Retrieves the bottommost nodes of the tree by recursively calling getEndPoints() on all children. If a child is null, it returns the parent as an end point. @return array
entailment
public function securityAction($name) { $parameters = $this->container->getParameter('youwe_file_manager'); $root = $parameters['upload_path']; $finfo = finfo_open(FILEINFO_MIME_TYPE); $upath = realpath($root); $ufiledir = $upath . '/' . $name; $ufilepath = realpath($ufiledir); if (substr($ufilepath, 0, strlen($upath)) == $upath) { $r = new Response(file_get_contents($ufilepath)); $r->headers->set('Content-Type', finfo_file($finfo, $ufilepath)); return $r; } throw $this->createNotFoundException('Error'); }
@author Roelf Otten @param $name @return int|Response @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
entailment
protected function _dispatch($method, $params=null, $source=null) { if($source) { if(($mapped=Zend_Amf_Parse_TypeLoader::getMappedClassName($source))!==false) { $source=$mapped; } } $qualifiedName=(empty($source) ? $method:$source.'.'.$method); if(!isset($this->_table[$qualifiedName])) { // if source is null a method that was not defined was called. if($source) { $className='CodeBank'.str_replace('.', '_', $source); if(class_exists($className, false) && !isset($this->_classAllowed[$className])) { require_once 'Zend/Amf/Server/Exception.php'; throw new Zend_Amf_Server_Exception('Can not call "'.$className.'" - use setClass()'); } try { $this->getLoader()->load($className); } catch (Exception $e) { require_once 'Zend/Amf/Server/Exception.php'; throw new Zend_Amf_Server_Exception('Class "'.$className.'" does not exist: '.$e->getMessage(), 0, $e); } // Add the new loaded class to the server. $this->setClass($className, $source); } if(!isset($this->_table[$qualifiedName])) { // Source is null or doesn't contain specified method require_once 'Zend/Amf/Server/Exception.php'; throw new Zend_Amf_Server_Exception('Method "'.$method.'" does not exist'); } } $info=$this->_table[$qualifiedName]; $argv=$info->getInvokeArguments(); if(0<count($argv)) { $params=array_merge($params, $argv); } if($info instanceof Zend_Server_Reflection_Function) { $func=$info->getName(); $this->_checkAcl(null, $func); $return=call_user_func_array($func, $params); }else if($info instanceof Zend_Server_Reflection_Method) { // Get class $class=$info->getDeclaringClass()->getName(); //Check permissions if($this->_canAccess($class)==false) { $response=CodeBank_ClientAPI::responseBase(); $response['status']='EROR'; $response['message']=_t('CodeBankAPI.PERMISSION_DENINED', '_Permission Denied'); return $response; } if('static'==$info->isStatic()) { // for some reason, invokeArgs() does not work the same as // invoke(), and expects the first argument to be an object. // So, using a callback if the method is static. $this->_checkAcl($class, $info->getName()); $return=call_user_func_array(array($class, $info->getName()), $params); }else { // Object methods try { $object=$info->getDeclaringClass()->newInstance(); }catch(Exception $e) { throw new Zend_Amf_Server_Exception('Error instantiating class '.$class.' to invoke method '.$info->getName().': '.$e->getMessage(), 621, $e); } $this->_checkAcl($object, $info->getName()); $return=$info->invokeArgs($object, $params); } }else { throw new Zend_Amf_Server_Exception('Method missing implementation '.get_class($info)); } return $return; }
Loads a remote class or method and executes the function and returns the result @param {string} $method Is the method to execute @param {mixed} $param values for the method @return {mixed} $response the result of executing the method @throws Zend_Amf_Server_Exception
entailment
protected function _buildDispatchTable() { $table=array(); foreach($this->_methods as $key=>$dispatchable) { if($dispatchable instanceof Zend_Server_Reflection_Function_Abstract) { $ns=str_replace('CodeBank', '', $dispatchable->getNamespace()); $name=$dispatchable->getName(); $name=(empty($ns) ? $name:$ns.'.'.$name); if(isset($table[$name])) { throw new Zend_Amf_Server_Exception('Duplicate method registered: '.$name); } $table[$name]=$dispatchable; continue; } if($dispatchable instanceof Zend_Server_Reflection_Class) { foreach($dispatchable->getMethods() as $method) { $ns=str_replace('CodeBank', '', $method->getNamespace()); $name=$method->getName(); $name=(empty($ns) ? $name:$ns.'.'.$name); if(isset($table[$name])) { throw new Zend_Amf_Server_Exception('Duplicate method registered: '.$name); } $table[$name]=$method; continue; } } } $this->_table=$table; }
(Re)Build the dispatch table. The dispatch table consists of a an array of method name => Zend_Server_Reflection_Function_Abstract pairs @return void
entailment
protected function _canAccess($object) { if(!is_object($object)) { $object=singleton($object); } //Ensure the object is an instance of CodeBank_APIClass if(!($object instanceof CodeBank_APIClass)) { //If in dev mode and object is an instance of ZendAmfServiceBrowser return true if(Director::isDev() && $object instanceof ZendAmfServiceBrowser) { return true; } return false; } //Fetch permissions from the object $perms=$object->getRequiredPermissions(); //Check to see if the permissions are not empty if(!empty($perms) && $perms!==false) { //Ensure we have an array, if not throw an exception if(!is_array($perms)) { throw new Zend_Amf_Exception('CodeBank_APIClass::getRequiredPermissions() Should return an array of permissions to check'); return false; } //Loop through and ensure the user has the required permissions return false if they are missing any foreach($perms as $permission) { if(!Permission::check($permission)) { return false; } } } return true; }
Checks to see if the member can access the requested class @param {string|CodeBank_APIClass} $object Name of the class to check or an instance of CodeBank_APIClass
entailment
protected function _connect($dbType, $dbDescription) { if(is_object($dbDescription)) { $dbDescription = get_object_vars($dbDescription); } return Zend_Db::factory($dbType, $dbDescription); }
Connect to the database @param string $dbType Database adapter type for Zend_Db @param array|object $dbDescription Adapter-specific connection settings @return Zend_Db_Adapter_Abstract @see Zend_Db::factory()
entailment
public function describeTable($dbType, $dbDescription, $tableName) { $db = $this->_connect($dbType, $dbDescription); return $db->describeTable($tableName); }
Describe database object. Usage example: $inspector->describeTable('Pdo_Mysql', array( 'host' => '127.0.0.1', 'username' => 'webuser', 'password' => 'xxxxxxxx', 'dbname' => 'test' ), 'mytable' ); @param string $dbType Database adapter type for Zend_Db @param array|object $dbDescription Adapter-specific connection settings @param string $tableName Table name @return array Table description @see Zend_Db::describeTable() @see Zend_Db::factory()
entailment
public function connect($dbType, $dbDescription) { $db = $this->_connect($dbType, $dbDescription); $db->listTables(); return true; }
Test database connection @param string $dbType Database adapter type for Zend_Db @param array|object $dbDescription Adapter-specific connection settings @return bool @see Zend_Db::factory()
entailment
public function getTables($dbType, $dbDescription) { $db = $this->_connect($dbType, $dbDescription); return $db->listTables(); }
Get the list of database tables @param string $dbType Database adapter type for Zend_Db @param array|object $dbDescription Adapter-specific connection settings @return array List of the tables
entailment
protected function mergeTemplateResources(TemplateResources $templateResources) { $this->stylesheets = array_merge($this->stylesheets, $templateResources->getStylesheets()); $this->headerScripts = array_merge($this->headerScripts, $templateResources->getHeaderScripts()); $this->headerIncludes = array_merge($this->headerIncludes, $templateResources->getHeaderIncludes()); $this->footerScripts = array_merge($this->footerScripts, $templateResources->getFooterScripts()); $this->footerIncludes = array_merge($this->footerIncludes, $templateResources->getFooterIncludes()); }
Merge a set of template resources @param TemplateResources $templateResources Template resources
entailment
public static function addCommonStylesheets($commonStylesheets) { foreach (GeneralUtility::trimExplode(',', $commonStylesheets, true) as $commonStylesheet) { $commonStylesheet = self::resolveUrl($commonStylesheet); if ($commonStylesheet) { self::$commonStylesheets[] = $commonStylesheet; } } }
Add common stylesheets @param string $commonStylesheets Common stylesheets
entailment
public static function addCommonHeaderScripts($commonHeaderScripts) { foreach (GeneralUtility::trimExplode(',', $commonHeaderScripts, true) as $commonHeaderScript) { $commonHeaderScript = self::resolveUrl($commonHeaderScript); if ($commonHeaderScript) { self::$commonHeaderScripts[] = $commonHeaderScript; } } }
Add common header scripts @param string $commonHeaderScripts Common header scripts
entailment
public static function addCommonFooterScripts($commonFooterScripts) { foreach (GeneralUtility::trimExplode(',', $commonFooterScripts, true) as $commonFooterScript) { $commonFooterScript = self::resolveUrl($commonFooterScript); if ($commonFooterScript) { self::$commonFooterScripts[] = $commonFooterScript; } } }
Add common footer scripts @param string $commonFooterScripts Common footer scripts
entailment
public function addStylesheet($url) { $url = self::resolveUrl($url); if ($url) { $this->stylesheets[self::hashResource($url)] = $url; } }
Add a CSS stylesheet @param string $url CSS stylesheet URL
entailment
protected static function resolveUrl($url) { $url = trim($url); if (strlen($url)) { if (preg_match('%^https?\:\/\/%', $url)) { return $url; } $absScript = GeneralUtility::getFileAbsFileName($url); if (is_file($absScript)) { return substr($absScript, strlen(PATH_site)); } } return null; }
Resolve a URL @param string $url URL @return bool|string Resolved URL
entailment
public function addHeaderScript($url) { $url = self::resolveUrl($url); if ($url) { $this->headerScripts[self::hashResource($url)] = $url; } }
Add a header JavaScript @param string $url Header JavaScript URL
entailment
public function addHeaderInclude($path) { $path = trim($path); if (strlen($path)) { $absPath = GeneralUtility::getFileAbsFileName($path); if (is_file($absPath)) { $include = file_get_contents($absPath); $this->headerIncludes[self::hashResource($include)] = $include; } } }
Add a header inclusion resource @param string $path Header inclusion path
entailment
public function addFooterScript($url) { $url = self::resolveUrl($url); if ($url) { $this->footerScripts[self::hashResource($url)] = $url; } }
Add a footer JavaScript @param string $path Footer JavaScript URL
entailment
public function addFooterInclude($path) { $path = trim($path); if (strlen($path)) { $absPath = GeneralUtility::getFileAbsFileName($path); if (is_file($absPath)) { $include = file_get_contents($absPath); $this->footerIncludes[self::hashResource($include)] = $include; } } }
Add a footer inclusion resource @param string $path Footer inclusion path
entailment
public function getTemplateResources() { return new TemplateResources( $this->stylesheets, $this->headerScripts, $this->headerIncludes, $this->footerScripts, $this->footerIncludes ); }
Return all template resources @return TemplateResources Template resources
entailment
public function authenticate() { if (empty($this->_request) || empty($this->_response)) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling ' . 'authenticate()'); } if ($this->_imaProxy) { $getHeader = 'Proxy-Authorization'; } else { $getHeader = 'Authorization'; } $authHeader = $this->_request->getHeader($getHeader); if (!$authHeader) { return $this->_challengeClient(); } list($clientScheme) = explode(' ', $authHeader); $clientScheme = strtolower($clientScheme); // The server can issue multiple challenges, but the client should // answer with only the selected auth scheme. if (!in_array($clientScheme, $this->_supportedSchemes)) { $this->_response->setHttpResponseCode(400); return new Zend_Auth_Result( Zend_Auth_Result::FAILURE_UNCATEGORIZED, array(), array('Client requested an incorrect or unsupported authentication scheme') ); } // client sent a scheme that is not the one required if (!in_array($clientScheme, $this->_acceptSchemes)) { // challenge again the client return $this->_challengeClient(); } switch ($clientScheme) { case 'basic': $result = $this->_basicAuth($authHeader); break; case 'digest': $result = $this->_digestAuth($authHeader); break; default: /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('Unsupported authentication scheme'); } return $result; }
Authenticate @throws Zend_Auth_Adapter_Exception @return Zend_Auth_Result
entailment
protected function _challengeClient() { if ($this->_imaProxy) { $statusCode = 407; $headerName = 'Proxy-Authenticate'; } else { $statusCode = 401; $headerName = 'WWW-Authenticate'; } $this->_response->setHttpResponseCode($statusCode); // Send a challenge in each acceptable authentication scheme if (in_array('basic', $this->_acceptSchemes)) { $this->_response->setHeader($headerName, $this->_basicHeader()); } if (in_array('digest', $this->_acceptSchemes)) { $this->_response->setHeader($headerName, $this->_digestHeader()); } return new Zend_Auth_Result( Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, array(), array('Invalid or absent credentials; challenging client') ); }
Challenge Client Sets a 401 or 407 Unauthorized response code, and creates the appropriate Authenticate header(s) to prompt for credentials. @return Zend_Auth_Result Always returns a non-identity Auth result
entailment
protected function _digestHeader() { $wwwauth = 'Digest realm="' . $this->_realm . '", ' . 'domain="' . $this->_domains . '", ' . 'nonce="' . $this->_calcNonce() . '", ' . ($this->_useOpaque ? 'opaque="' . $this->_calcOpaque() . '", ' : '') . 'algorithm="' . $this->_algo . '", ' . 'qop="' . implode(',', $this->_supportedQops) . '"'; return $wwwauth; }
Digest Header Generates a Proxy- or WWW-Authenticate header value in the Digest authentication scheme. @return string Authenticate header value
entailment
protected function _basicAuth($header) { if (empty($header)) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required'); } if (empty($this->_basicResolver)) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('A basicResolver object must be set before doing Basic ' . 'authentication'); } // Decode the Authorization header $auth = substr($header, strlen('Basic ')); $auth = base64_decode($auth); if (!$auth) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('Unable to base64_decode Authorization header value'); } // See ZF-1253. Validate the credentials the same way the digest // implementation does. If invalid credentials are detected, // re-challenge the client. if (!ctype_print($auth)) { return $this->_challengeClient(); } // Fix for ZF-1515: Now re-challenges on empty username or password $creds = array_filter(explode(':', $auth)); if (count($creds) != 2) { return $this->_challengeClient(); } $password = $this->_basicResolver->resolve($creds[0], $this->_realm); if ($password && $this->_secureStringCompare($password, $creds[1])) { $identity = array('username'=>$creds[0], 'realm'=>$this->_realm); return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity); } else { return $this->_challengeClient(); } }
Basic Authentication @param string $header Client's Authorization header @throws Zend_Auth_Adapter_Exception @return Zend_Auth_Result
entailment
protected function _digestAuth($header) { if (empty($header)) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required'); } if (empty($this->_digestResolver)) { /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('A digestResolver object must be set before doing Digest authentication'); } $data = $this->_parseDigestAuth($header); if ($data === false) { $this->_response->setHttpResponseCode(400); return new Zend_Auth_Result( Zend_Auth_Result::FAILURE_UNCATEGORIZED, array(), array('Invalid Authorization header format') ); } // See ZF-1052. This code was a bit too unforgiving of invalid // usernames. Now, if the username is bad, we re-challenge the client. if ('::invalid::' == $data['username']) { return $this->_challengeClient(); } // Verify that the client sent back the same nonce if ($this->_calcNonce() != $data['nonce']) { return $this->_challengeClient(); } // The opaque value is also required to match, but of course IE doesn't // play ball. if (!$this->_ieNoOpaque && $this->_calcOpaque() != $data['opaque']) { return $this->_challengeClient(); } // Look up the user's password hash. If not found, deny access. // This makes no assumptions about how the password hash was // constructed beyond that it must have been built in such a way as // to be recreatable with the current settings of this object. $ha1 = $this->_digestResolver->resolve($data['username'], $data['realm']); if ($ha1 === false) { return $this->_challengeClient(); } // If MD5-sess is used, a1 value is made of the user's password // hash with the server and client nonce appended, separated by // colons. if ($this->_algo == 'MD5-sess') { $ha1 = hash('md5', $ha1 . ':' . $data['nonce'] . ':' . $data['cnonce']); } // Calculate h(a2). The value of this hash depends on the qop // option selected by the client and the supported hash functions switch ($data['qop']) { case 'auth': $a2 = $this->_request->getMethod() . ':' . $data['uri']; break; case 'auth-int': // Should be REQUEST_METHOD . ':' . uri . ':' . hash(entity-body), // but this isn't supported yet, so fall through to default case default: /** * @see Zend_Auth_Adapter_Exception */ require_once 'Zend/Auth/Adapter/Exception.php'; throw new Zend_Auth_Adapter_Exception('Client requested an unsupported qop option'); } // Using hash() should make parameterizing the hash algorithm // easier $ha2 = hash('md5', $a2); // Calculate the server's version of the request-digest. This must // match $data['response']. See RFC 2617, section 3.2.2.1 $message = $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $ha2; $digest = hash('md5', $ha1 . ':' . $message); // If our digest matches the client's let them in, otherwise return // a 401 code and exit to prevent access to the protected resource. if ($this->_secureStringCompare($digest, $data['response'])) { $identity = array('username'=>$data['username'], 'realm'=>$data['realm']); return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity); } else { return $this->_challengeClient(); } }
Digest Authentication @param string $header Client's Authorization header @throws Zend_Auth_Adapter_Exception @return Zend_Auth_Result Valid auth result only on successful auth
entailment
protected function _calcNonce() { // Once subtle consequence of this timeout calculation is that it // actually divides all of time into _nonceTimeout-sized sections, such // that the value of timeout is the point in time of the next // approaching "boundary" of a section. This allows the server to // consistently generate the same timeout (and hence the same nonce // value) across requests, but only as long as one of those // "boundaries" is not crossed between requests. If that happens, the // nonce will change on its own, and effectively log the user out. This // would be surprising if the user just logged in. $timeout = ceil(time() / $this->_nonceTimeout) * $this->_nonceTimeout; $nonce = hash('md5', $timeout . ':' . $this->_request->getServer('HTTP_USER_AGENT') . ':' . __CLASS__); return $nonce; }
Calculate Nonce @return string The nonce value
entailment
protected function _parseDigestAuth($header) { $temp = null; $data = array(); // See ZF-1052. Detect invalid usernames instead of just returning a // 400 code. $ret = preg_match('/username="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1]) || !ctype_print($temp[1]) || strpos($temp[1], ':') !== false) { $data['username'] = '::invalid::'; } else { $data['username'] = $temp[1]; } $temp = null; $ret = preg_match('/realm="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (!ctype_print($temp[1]) || strpos($temp[1], ':') !== false) { return false; } else { $data['realm'] = $temp[1]; } $temp = null; $ret = preg_match('/nonce="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (!ctype_xdigit($temp[1])) { return false; } else { $data['nonce'] = $temp[1]; } $temp = null; $ret = preg_match('/uri="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } // Section 3.2.2.5 in RFC 2617 says the authenticating server must // verify that the URI field in the Authorization header is for the // same resource requested in the Request Line. $rUri = @parse_url($this->_request->getRequestUri()); $cUri = @parse_url($temp[1]); if (false === $rUri || false === $cUri) { return false; } else { // Make sure the path portion of both URIs is the same if ($rUri['path'] != $cUri['path']) { return false; } // Section 3.2.2.5 seems to suggest that the value of the URI // Authorization field should be made into an absolute URI if the // Request URI is absolute, but it's vague, and that's a bunch of // code I don't want to write right now. $data['uri'] = $temp[1]; } $temp = null; $ret = preg_match('/response="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (32 != strlen($temp[1]) || !ctype_xdigit($temp[1])) { return false; } else { $data['response'] = $temp[1]; } $temp = null; // The spec says this should default to MD5 if omitted. OK, so how does // that square with the algo we send out in the WWW-Authenticate header, // if it can easily be overridden by the client? $ret = preg_match('/algorithm="?(' . $this->_algo . ')"?/', $header, $temp); if ($ret && !empty($temp[1]) && in_array($temp[1], $this->_supportedAlgos)) { $data['algorithm'] = $temp[1]; } else { $data['algorithm'] = 'MD5'; // = $this->_algo; ? } $temp = null; // Not optional in this implementation $ret = preg_match('/cnonce="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (!ctype_print($temp[1])) { return false; } else { $data['cnonce'] = $temp[1]; } $temp = null; // If the server sent an opaque value, the client must send it back if ($this->_useOpaque) { $ret = preg_match('/opaque="([^"]+)"/', $header, $temp); if (!$ret || empty($temp[1])) { // Big surprise: IE isn't RFC 2617-compliant. if (false !== strpos($this->_request->getHeader('User-Agent'), 'MSIE')) { $temp[1] = ''; $this->_ieNoOpaque = true; } else { return false; } } // This implementation only sends MD5 hex strings in the opaque value if (!$this->_ieNoOpaque && (32 != strlen($temp[1]) || !ctype_xdigit($temp[1]))) { return false; } else { $data['opaque'] = $temp[1]; } $temp = null; } // Not optional in this implementation, but must be one of the supported // qop types $ret = preg_match('/qop="?(' . implode('|', $this->_supportedQops) . ')"?/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (!in_array($temp[1], $this->_supportedQops)) { return false; } else { $data['qop'] = $temp[1]; } $temp = null; // Not optional in this implementation. The spec says this value // shouldn't be a quoted string, but apparently some implementations // quote it anyway. See ZF-1544. $ret = preg_match('/nc="?([0-9A-Fa-f]{8})"?/', $header, $temp); if (!$ret || empty($temp[1])) { return false; } if (8 != strlen($temp[1]) || !ctype_xdigit($temp[1])) { return false; } else { $data['nc'] = $temp[1]; } $temp = null; return $data; }
Parse Digest Authorization header @param string $header Client's Authorization: HTTP header @return array|false Data elements from header, or false if any part of the header is invalid
entailment
public function handle(DomainEvent $event) : void { $method = lcfirst($this->getShortName($event)); if (method_exists($this, $method)) { $this->$method($event); } }
receives domain events and routes them to a method with their name @param DomainEvent $event
entailment
public function createGraph($graph) { // Write the dot source to a temporary file $tempDot = tempnam(sys_get_temp_dir(), 'DOT_'); $this->registerTempFile($tempDot); file_put_contents($tempDot, $graph); // Create component graph // $dotCommand = 'ccomps -x '.CommandUtility::escapeShellArgument($tempDot).' | dot -Nfontname=sans-serif -Efontname=sans-serif | gvpack -array_1 | neato -Tsvg '; $dotCommand = 'dot -Tsvg -Nfontname=sans-serif -Efontname=sans-serif '.CommandUtility::escapeShellArgument($tempDot); $output = $returnValue = null; CommandUtility::exec($dotCommand, $output, $returnValue); return $returnValue ? '' : implode('', (array)$output); }
Create an SVG component graph @param string $graph GraphViz graph @return string SVG component graph @see https://stackoverflow.com/questions/8002352/how-to-control-subgraphs-layout-in-dot
entailment
public function thumb($path) { try{ $cacheManager = $this->container->get('liip_imagine.cache.manager'); $filter = FileManager::FILTER_NAME; return new \Twig_Markup( $cacheManager->getBrowserPath($path, $filter, array()), 'utf8' ); } catch(\Exception $e){ return $path; } }
Gets the browser path for the image and filter to apply. @param string $path @return \Twig_Markup
entailment
public function key($name): string { if ( ! isset($this->details[$name])) { throw new CryptographicDetailsDoNotContainKey($name); } return $this->details[$name]; }
get the value for a key from the cryptographic details @param $name @return string @throws CryptographicDetailsDoNotContainKey
entailment
public function serialize(): array { // base 64 encode $details = array_map(function($value) { return base64_encode($value); }, $this->details); // enrich with encryption type return $details + ['encryption' => $this->encryption]; }
serialize() returns an associated array form of the value for persistence which will be deserialized when needed. the array should contain primitives for both keys and values. @return array
entailment
public static function deserialize(array $data): CryptographicDetails { // json string to array if ( ! isset($data['encryption'])) { throw new CannotDeserializeCryptographicDetails('Encryption type could not be identified from serialized form.'); } // pull out the encryption key $encryption = $data['encryption']; unset($data['encryption']); // base64 decode $details = array_map(function($value) { return base64_decode($value); }, $data); return new static($encryption, $details); }
deserialize() returns a value object from an associative array received from persistence @param array $data @return mixed @throws CannotDeserializeCryptographicDetails
entailment
public function index() { //Ensure the session is started Session::start(); //Start the server $server=new CodeBankAMFServer(); //Initialize the server classes $classes=ClassInfo::implementorsOf('CodeBank_APIClass'); foreach($classes as $class) { //Set the class to be active in the server $server->setClass($class); } //Enable Service Browser if in dev mode if(Director::isDev()) { $server->setClass('ZendAmfServiceBrowser'); ZendAmfServiceBrowser::$ZEND_AMF_SERVER=$server; } if(class_exists('CodeBankAPITest') && $this->_testAMFRequest!==false) { $server->setRequest($this->_testAMFRequest); $server->setResponse(new Zend_Amf_Response()); } $server->setProduction(!Director::isDev()); //Server debug, bind to opposite of Director::isDev() //Start the response $response=$server->handle(); //If not in test mode add the application/x-amf content type if(!class_exists('CodeBankAPITest')) { $this->response->addHeader('Content-Type', 'application/x-amf'); } //Save session Session::save(); //Output return $response; }
Handles all amf requests
entailment
public function export_snippet(SS_HTTPRequest $request) { if($request->getVar('s')) { //Use the session id in the request Session::start($request->getVar('s')); } if(!Permission::check('CODE_BANK_ACCESS')) { header("HTTP/1.1 401 Unauthorized"); //Save session and exit Session::save(); exit; } try { $snippet=Snippet::get()->byID(intval($request->getVar('id'))); if(empty($snippet) || $snippet===false || $snippet->ID==0) { header("HTTP/1.1 404 Not Found"); //Save session and exit Session::save(); exit; } $urlFilter=URLSegmentFilter::create(); $fileID=$urlFilter->filter($snippet->Title); //If the temp dir doesn't exist create it if(!file_exists(ASSETS_PATH.'/.codeBankTemp')) { mkdir(ASSETS_PATH.'/.codeBankTemp', Config::inst()->get('Filesystem', 'folder_create_mask')); } if($snippet->Language()->Name=='ActionScript 3') { $zip=new ZipArchive(); $res=$zip->open(ASSETS_PATH.'/.codeBankTemp/'.$fileID.'.zip', ZIPARCHIVE::CREATE); if($res===true) { $path=''; $text=preg_split("/[\n\r]/", $snippet->getSnippetText()); $folder=str_replace('.', '/', trim(preg_replace('/^package (.*?)((\s*)\{)?$/i', '\\1', $text[0]))); $className=array_values(preg_grep('/(\s*|\t*)public(\s+)class(\s+)(.*?)(\s*)((extends|implements)(.*?)(\s*))*\{/i', $text)); if(count($className)==0) { throw new Exception('Class definition could not be found'); } $className=trim(preg_replace('/(\s*|\t*)public(\s+)class(\s+)(.*?)(\s*)((extends|implements)(.*?)(\s*))*\{/i','\\4', $className[0])); if($className=="") { throw new Exception('Class definition could not be found'); } $zip->addFromString($folder.'/'.$className.'.'.$snippet->Language()->FileExtension, $snippet->getSnippetText()); if($zip->Close()!==false) { chmod(ASSETS_PATH.'/.codeBankTemp/'.$fileID.'.zip',0600); //Send File SS_HTTPRequest::send_file(file_get_contents(ASSETS_PATH.'/.codeBankTemp/'.$fileID.'.zip'), $fileID.'.zip', 'application/octet-stream')->output(); unlink(ASSETS_PATH.'/.codeBankTemp/'.$fileID.'.zip'); }else { header("HTTP/1.1 500 Internal Server Error"); } }else { header("HTTP/1.1 500 Internal Server Error"); } }else { SS_HTTPRequest::send_file($snippet->getSnippetText(), $fileID.'.'.$snippet->Language()->FileExtension, 'text/plain')->output(); } }catch (Exception $e) { header("HTTP/1.1 500 Internal Server Error"); } //Save session and exit Session::save(); exit; }
Handles exporting of snippets @param {SS_HTTPRequest} $request HTTP Request Data
entailment
public function export_to_client() { if(!Permission::check('CODE_BANK_ACCESS')) { return Security::permissionFailure($this); } //Bump up time limit we may need it set_time_limit(480); //Dump Data $languages=$this->queryToArray(DB::query('SELECT "ID", "Name", "FileExtension", "HighlightCode", "UserLanguage" FROM "SnippetLanguage"')); $snippets=$this->queryToArray(DB::query('SELECT "ID", "Title", "Description", "Tags", "LanguageID", "PackageID", "FolderID" FROM "Snippet"')); $versions=$this->queryToArray(DB::query('SELECT "ID", "Created", "Text", "ParentID" FROM "SnippetVersion"')); $packages=$this->queryToArray(DB::query('SELECT "ID", "Title" FROM "SnippetPackage"')); $folders=$this->queryToArray(DB::query('SELECT "ID", "Name", "ParentID", "LanguageID" FROM "SnippetFolder"')); //Build final response array $response=array( 'format'=>'ToClient', 'data'=>array( 'languages'=>$languages, 'snippets'=>$snippets, 'versions'=>$versions, 'packages'=>$packages, 'folders'=>$folders ) ); //Send File SS_HTTPRequest::send_file(json_encode($response), date('Y-m-d_hi').'.cbexport', 'application/json')->output(); //Save session and exit Session::save(); exit; }
Builds a json export file for importing on the client
entailment
private function queryToArray(SS_Query $source) { $result=array(); foreach($source as $row) { $result[]=$row; } return $result; }
Merges a database resultset into an array @param {SS_Query} $source SS_Query containing the result set @return {array} Merged array
entailment
final protected function getVersion() { if(CB_VERSION!='@@VERSION@@') { return CB_VERSION.' '.CB_BUILD_DATE; } // Tries to obtain version number from composer.lock if it exists $composerLockPath=BASE_PATH.'/composer.lock'; if(file_exists($composerLockPath)) { $cache=SS_Cache::factory('CodeBank_Version'); $cacheKey=filemtime($composerLockPath); $version=$cache->load($cacheKey); if($version) { $version=$version; }else { $version=''; } if(!$version && $jsonData=file_get_contents($composerLockPath)) { $lockData=json_decode($jsonData); if($lockData && isset($lockData->packages)) { foreach ($lockData->packages as $package) { if($package->name=='undefinedoffset/silverstripe-codebank' && isset($package->version)) { $version=$package->version; break; } } $cache->save($version, $cacheKey); } } } if(!empty($version)) { return $version; } return _t('CodeBank.DEVELOPMENT_BUILD', '_Development Build'); }
Gets the current version of Code Bank @return {string} Version Number Plus Build Date
entailment
public function useFileLogger(string $dir): self { $this->setLogger(new \BearFramework\App\FileLogger($dir)); return $this; }
Enables a file logger for directory specified. @param string $dir The directory where the logs will be stored. @return self Returns a reference to itself.
entailment
public function setLogger(\BearFramework\App\ILogger $logger): self { if ($this->logger !== null) { throw new \Exception('A logger is already set!'); } $this->logger = $logger; return $this; }
Sets a new logger. @param \BearFramework\App\ILogger $logger The logger to use. @return self Returns a reference to itself. @throws \Exception
entailment
private function getLogger(): \BearFramework\App\ILogger { if ($this->logger !== null) { return $this->logger; } throw new \Exception('No logger specified! Use useFileLogger() or setLogger() to specify one.'); }
Returns the logger. @return \BearFramework\App\ILogger @throws \Exception
entailment
public function log(string $name, string $message, array $data = []): self { $name = trim((string) $name); if (strlen($name) === 0) { throw new \InvalidArgumentException('The name argument must not be empty!'); } $logger = $this->getLogger(); $logger->log($name, $message, $data); return $this; }
Logs the data specified. @param string $name The name of the log context. @param string $message The message that will be logged. @param array $data Additional information to log. @throws \InvalidArgumentException @return self Returns a reference to itself.
entailment
protected function loadFile($file) { $data = @json_decode(@file_get_contents($file), true); if (json_last_error() !== JSON_ERROR_NONE) { throw new \InvalidArgumentException(json_last_error_msg()); } if (!is_array($data)) { throw new \InvalidArgumentException(sprintf('The json mapping file "%s" is not valid.', $file)); } return $data; }
{@inheritdoc}
entailment
public function useFileDriver(string $dir): self { $this->setDriver(new \BearFramework\App\FileDataDriver($dir)); return $this; }
Enables the file data driver using the directory specified. @param string $dir The directory used for file storage. @return self Returns a reference to itself.
entailment
public function setDriver(\BearFramework\App\IDataDriver $driver): self { if ($this->driver !== null) { throw new \Exception('A data driver is already set!'); } $this->driver = $driver; if ($this->filenameProtocol !== null) { \BearFramework\Internal\DataItemStreamWrapper::$environment[$this->filenameProtocol] = [$this, $driver]; } return $this; }
Sets a new data driver. @param \BearFramework\App\IDataDriver $driver The data driver to use for data storage. @return self Returns a reference to itself. @throws \Exception
entailment
private function getDriver(): \BearFramework\App\IDataDriver { if ($this->driver !== null) { return $this->driver; } throw new \Exception('No data driver specified! Use useFileDriver() or setDriver() to specify one.'); }
Returns the data driver. @return \BearFramework\App\IDataDriver @throws \Exception
entailment
public function make(string $key = null, string $value = null): \BearFramework\App\DataItem { if ($this->newDataItemCache === null) { $this->newDataItemCache = new \BearFramework\App\DataItem(); } $object = clone($this->newDataItemCache); if ($key !== null) { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $object->key = $key; } if ($value !== null) { $object->value = $value; } return $object; }
Constructs a new data item and returns it. @param string|null $key The key of the data item. @param string|null $value The value of the data item. @return \BearFramework\App\DataItem Returns a new data item. @throws \InvalidArgumentException
entailment
public function set(DataItem $item): self { if ($item->key === null || !$this->validate($item->key)) { throw new \InvalidArgumentException('The key provided (' . ($item->key === null ? 'null' : $item->key) . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $metadataAsArray = $item->metadata->toArray(); foreach ($metadataAsArray as $name => $value) { if (!$this->validateMetadataName($name)) { throw new \InvalidArgumentException('The metadata name provided (' . $name . ') is not valid! It may contain only the following characters: "a-z", "A-Z", "0-9", ".", "-" and "_".'); } } $driver = $this->getDriver(); $driver->set($item); if ($this->hasEventListeners('itemSet')) { $this->dispatchEvent('itemSet', new \BearFramework\App\Data\ItemSetEventDetails(clone($item))); } if ($this->hasEventListeners('itemChange')) { $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($item->key)); } return $this; }
Stores a data item. @param \BearFramework\App\DataItem $item The data item to store. @return self Returns a reference to itself. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function setValue(string $key, string $value): self { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $driver = $this->getDriver(); $driver->setValue($key, $value); if ($this->hasEventListeners('itemSetValue')) { $this->dispatchEvent('itemSetValue', new \BearFramework\App\Data\ItemSetValueEventDetails($key, $value)); } if ($this->hasEventListeners('itemChange')) { $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($key)); } return $this; }
Sets a new value of the item specified or creates a new item with the key and value specified. @param string $key The key of the data item. @param string $value The value of the data item. @return self Returns a reference to itself. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function get(string $key): ?\BearFramework\App\DataItem { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $driver = $this->getDriver(); $item = $driver->get($key); if ($this->hasEventListeners('itemGet')) { $this->dispatchEvent('itemGet', new \BearFramework\App\Data\ItemGetEventDetails($key, $item === null ? null : clone($item))); } if ($this->hasEventListeners('itemRequest')) { $this->dispatchEvent('itemRequest', new \BearFramework\App\Data\ItemRequestEventDetails($key)); } return $item; }
Returns a stored data item or null if not found. @param string $key The key of the stored data item. @return \BearFramework\App\DataItem|null A data item or null if not found. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function getValue(string $key): ?string { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $driver = $this->getDriver(); $value = $driver->getValue($key); if ($this->hasEventListeners('itemGetValue')) { $this->dispatchEvent('itemGetValue', new \BearFramework\App\Data\ItemGetValueEventDetails($key, $value)); } if ($this->hasEventListeners('itemRequest')) { $this->dispatchEvent('itemRequest', new \BearFramework\App\Data\ItemRequestEventDetails($key)); } return $value; }
Returns the value of a stored data item or null if not found. @param string $key The key of the stored data item. @return string|null The value of a stored data item or null if not found. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function exists(string $key): bool { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $driver = $this->getDriver(); $exists = $driver->exists($key); if ($this->hasEventListeners('itemExists')) { $this->dispatchEvent('itemExists', new \BearFramework\App\Data\ItemExistsEventDetails($key, $exists)); } if ($this->hasEventListeners('itemRequest')) { $this->dispatchEvent('itemRequest', new \BearFramework\App\Data\ItemRequestEventDetails($key)); } return $exists; }
Returns TRUE if the data item exists. FALSE otherwise. @param string $key The key of the stored data item. @return bool TRUE if the data item exists. FALSE otherwise. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function append(string $key, string $content): self { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $driver = $this->getDriver(); $driver->append($key, $content); if ($this->hasEventListeners('itemAppend')) { $this->dispatchEvent('itemAppend', new \BearFramework\App\Data\ItemAppendEventDetails($key, $content)); } if ($this->hasEventListeners('itemChange')) { $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($key)); } return $this; }
Appends data to the data item's value specified. If the data item does not exist, it will be created. @param string $key The key of the data item. @param string $content The content to append. @return self Returns a reference to itself. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function duplicate(string $sourceKey, string $destinationKey): self { if (!$this->validate($sourceKey)) { throw new \InvalidArgumentException('The key provided (' . $sourceKey . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } if (!$this->validate($destinationKey)) { throw new \InvalidArgumentException('The key provided (' . $destinationKey . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $driver = $this->getDriver(); $driver->duplicate($sourceKey, $destinationKey); if ($this->hasEventListeners('itemDuplicate')) { $this->dispatchEvent('itemDuplicate', new \BearFramework\App\Data\ItemDuplicateEventDetails($sourceKey, $destinationKey)); } if ($this->hasEventListeners('itemRequest')) { $this->dispatchEvent('itemRequest', new \BearFramework\App\Data\ItemRequestEventDetails($sourceKey)); } if ($this->hasEventListeners('itemChange')) { $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($destinationKey)); } return $this; }
Creates a copy of the data item specified. @param string $sourceKey The key of the source data item. @param string $destinationKey The key of the destination data item. @return self Returns a reference to itself. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function rename(string $sourceKey, string $destinationKey): self { if (!$this->validate($sourceKey)) { throw new \InvalidArgumentException('The key provided (' . $sourceKey . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } if (!$this->validate($destinationKey)) { throw new \InvalidArgumentException('The key provided (' . $destinationKey . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $driver = $this->getDriver(); $driver->rename($sourceKey, $destinationKey); if ($this->hasEventListeners('itemRename')) { $this->dispatchEvent('itemRename', new \BearFramework\App\Data\ItemRenameEventDetails($sourceKey, $destinationKey)); } if ($this->hasEventListeners('itemChange')) { $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($sourceKey)); $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($destinationKey)); } return $this; }
Changes the key of the data item specified. @param string $sourceKey The current key of the data item. @param string $destinationKey The new key of the data item. @return self Returns a reference to itself. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function delete(string $key): self { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } $driver = $this->getDriver(); $driver->delete($key); if ($this->hasEventListeners('itemDelete')) { $this->dispatchEvent('itemDelete', new \BearFramework\App\Data\ItemDeleteEventDetails($key)); } if ($this->hasEventListeners('itemChange')) { $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($key)); } return $this; }
Deletes the data item specified and it's metadata. @param string $key The key of the data item to delete. @return self Returns a reference to itself. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function setMetadata(string $key, string $name, string $value): self { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } if (!$this->validateMetadataName($name)) { throw new \InvalidArgumentException('The metadata name provided (' . $name . ') is not valid! It may contain only the following characters: "a-z", "A-Z", "0-9", ".", "-" and "_".'); } $driver = $this->getDriver(); $driver->setMetadata($key, $name, $value); if ($this->hasEventListeners('itemSetMetadata')) { $this->dispatchEvent('itemSetMetadata', new \BearFramework\App\Data\ItemSetMetadataEventDetails($key, $name, $value)); } if ($this->hasEventListeners('itemChange')) { $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($key)); } return $this; }
Stores metadata for the data item specified. @param string $key The key of the data item. @param string $name The metadata name. @param string $value The metadata value. @return self Returns a reference to itself. @throws \Exception @throws \InvalidArgumentException @throws \BearFramework\App\Data\DataLockedException
entailment
public function getMetadata(string $key, string $name): ?string { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } if (!$this->validateMetadataName($name)) { throw new \InvalidArgumentException('The metadata name provided (' . $name . ') is not valid! It may contain only the following characters: "a-z", "A-Z", "0-9", ".", "-" and "_".'); } $driver = $this->getDriver(); $value = $driver->getMetadata($key, $name); if ($this->hasEventListeners('itemGetMetadata')) { $this->dispatchEvent('itemGetMetadata', new \BearFramework\App\Data\ItemGetMetadataEventDetails($key, $name, $value)); } if ($this->hasEventListeners('itemRequest')) { $this->dispatchEvent('itemRequest', new \BearFramework\App\Data\ItemRequestEventDetails($key)); } return $value; }
Retrieves metadata for the data item specified. @param string $key The data item key. @param string $name The metadata name. @return string|null The value of the data item metadata. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function deleteMetadata(string $key, string $name): self { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } if (!$this->validateMetadataName($name)) { throw new \InvalidArgumentException('The metadata name provided (' . $name . ') is not valid! It may contain only the following characters: "a-z", "A-Z", "0-9", ".", "-" and "_".'); } $driver = $this->getDriver(); $driver->deleteMetadata($key, $name); if ($this->hasEventListeners('itemDeleteMetadata')) { $this->dispatchEvent('itemDeleteMetadata', new \BearFramework\App\Data\ItemDeleteMetadataEventDetails($key, $name)); } if ($this->hasEventListeners('itemChange')) { $this->dispatchEvent('itemChange', new \BearFramework\App\Data\ItemChangeEventDetails($key)); } return $this; }
Deletes metadata for the data item key specified. @param string $key The data item key. @param string $name The metadata name. @return self Returns a reference to itself. @throws \Exception @throws \BearFramework\App\Data\DataLockedException @throws \InvalidArgumentException
entailment
public function getList(): \BearFramework\DataList { $list = new \BearFramework\DataList(function(\BearFramework\DataList\Context $context) { $driver = $this->getDriver(); return $driver->getList($context); }); if ($this->hasEventListeners('getList')) { $this->dispatchEvent('getList', new \BearFramework\App\Data\GetListEventDetails($list)); } return $list; }
Returns a list of all items in the data storage. @return \BearFramework\DataList|\BearFramework\App\DataItem[] A list of all items in the data storage. @throws \Exception @throws \BearFramework\App\Data\DataLockedException
entailment
public function getFilename(string $key): string { if (!$this->validate($key)) { throw new \InvalidArgumentException('The key provided (' . $key . ') is not valid! It may contain only the following characters: "a-z", "0-9", ".", "/", "-" and "_".'); } if ($this->filenameProtocol === null) { throw new \Exception('No filenameProtocol specified!'); } return $this->filenameProtocol . '://' . $key; }
Returns the filename of the data item specified. @param string $key The key of the data item. @return string The filename of the data item specified. @throws \Exception @throws \InvalidArgumentException
entailment
static function register(string $id, string $dir, $options = []): bool { if (isset(self::$data[$id])) { return false; } if (!isset($id{0})) { throw new \InvalidArgumentException('The value of the id argument cannot be empty.'); } $dir = rtrim(\BearFramework\Internal\Utilities::normalizePath($dir), '/'); if (!is_dir($dir)) { throw new \InvalidArgumentException('The value of the dir argument is not a valid directory.'); } self::$data[$id] = new \BearFramework\Addon($id, $dir, $options); return true; }
Registers an addon. @param string $id The id of the addon. @param string $dir The directory where the addon files are located. @param array $options The addon options. Available values: - require - An array containing the ids of addons that must be added before this one. @return bool TRUE if successfully registered. FALSE otherwise.
entailment
static function get(string $id): ?\BearFramework\Addon { if (isset(self::$data[$id])) { return clone(self::$data[$id]); } return null; }
Returns information about the addon specified. @param string $id The id of the addon. @return \BearFramework\Addon|null Information about the addon requested or null if not found.
entailment
static function getList() { $list = new \BearFramework\DataList(); foreach (self::$data as $addon) { $list[] = clone($addon); } return $list; }
Returns a list of all registered addons. @return \BearFramework\DataList|\BearFramework\Addon[] A list of all registered addons.
entailment
public function make(string $name = null, string $value = null): \BearFramework\App\Response\Cookie { if ($this->newCookieCache === null) { $this->newCookieCache = new \BearFramework\App\Response\Cookie(); } $object = clone($this->newCookieCache); if ($name !== null) { $object->name = $name; } if ($value !== null) { $object->value = $value; } return $object; }
Constructs a new cookie and returns it. @param string|null $name The name of the cookie. @param string|null $value The value of the cookie. @return \BearFramework\App\Response\Cookie Returns a new cookie.
entailment
public function set(\BearFramework\App\Response\Cookie $cookie): self { $this->data[$cookie->name] = $cookie; return $this; }
Sets a cookie. @param \BearFramework\App\Response\Cookie $cookie The cookie to set. @return self Returns a reference to itself.
entailment
public function get(string $name): ?\BearFramework\App\Response\Cookie { if (isset($this->data[$name])) { return clone($this->data[$name]); } return null; }
Returns a cookie or null if not found. @param string $name The name of the cookie. @return BearFramework\App\Response\Cookie|null The cookie requested of null if not found.
entailment
public function delete(string $name): self { if (isset($this->data[$name])) { unset($this->data[$name]); } return $this; }
Deletes a cookie if exists. @param string $name The name of the cookie to delete. @return self Returns a reference to itself.
entailment
public function getList() { $list = new \BearFramework\DataList(); foreach ($this->data as $cookie) { $list[] = clone($cookie); } return $list; }
Returns a list of all cookies. @return \BearFramework\DataList|\BearFramework\App\Response\Cookie[] An array containing all cookies.
entailment
public function convert($data, TypeMetadataInterface $type, ContextInterface $context) { return $context->getVisitor()->visitResource($data, $type, $context); }
{@inheritdoc}
entailment
public function parse($type) { $type = trim($type); if (empty($type)) { throw new \InvalidArgumentException('The type must be a non empty string.'); } $this->lexer->setInput($type); $this->walk(); try { return $this->parseType(); } catch (\Exception $e) { throw new \InvalidArgumentException(sprintf('The type "%s" is not valid.', $type), 0, $e); } }
{@inheritdoc}
entailment
private function validateToken($type) { $token = $this->lexer->token; if ($token['type'] !== $type) { throw new \InvalidArgumentException(sprintf( 'Expected a token type "%d", got "%d".', TypeLexer::T_LOWER_THAN, $token['type'] )); } $this->walk(); return $token; }
@param int $type @return mixed[]
entailment
private function walk($count = 1) { $token = $nextToken = $this->lexer->token; for ($i = 0; ($i < $count) || ($token === $nextToken); ++$i) { $this->lexer->moveNext(); $nextToken = $this->lexer->token; } return $nextToken; }
@param int $count @return mixed[]
entailment