sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function setMask(int $mask): ZipManager { try { foreach ( $this->zip_archives as $archive ) { $archive->setMask($mask); } return $this; } catch (ZipException $ze) { throw $ze; } }
Set default file mask for all Zips @param int $mask @return ZipManager @throws ZipException
entailment
public function getMask(): array { return array_column( array_map(function($key, $archive) { return [ "key" => $key, "mask" => $archive->getMask() ]; }, array_keys($this->zip_archives), $this->zip_archives), "mask", "key"); }
Get a list of masks from Zips @return array
entailment
public function listFiles(): array { try { return array_column( array_map(function($key, $archive) { return [ "key" => $key, "files" => $archive->listFiles() ]; }, array_keys($this->zip_archives), $this->zip_archives), "files", "key"); } catch (ZipException $ze) { throw $ze; } }
Get a list of files in Zips @return array @throws ZipException
entailment
public function extract( string $destination, bool $separate = true, $files = null ): bool { try { foreach ( $this->zip_archives as $archive ) { $local_path = substr($destination, -1) == '/' ? $destination : $destination.'/'; $local_file = pathinfo($archive->getZipFile()); $local_destination = $separate ? ($local_path.$local_file['filename']) : $destination; $archive->extract($local_destination, $files); } return true; } catch (ZipException $ze) { throw $ze; } }
Extract Zips to common destination @param string $destination Destination path @param bool $separate (optional) If true (default), files will be placed in different directories @param mixed $files (optional) a filename or an array of filenames @return bool @throws ZipException
entailment
public function merge(string $output_zip_file, bool $separate = true): bool { $pathinfo = pathinfo($output_zip_file); $temporary_folder = $pathinfo['dirname']."/".ManagerTools::getTemporaryFolder(); try { $this->extract($temporary_folder, $separate); $zip = Zip::create($output_zip_file); $zip->add($temporary_folder, true)->close(); ManagerTools::recursiveUnlink($temporary_folder); return true; } catch (ZipException $ze) { throw $ze; } catch (Exception $e) { throw $e; } }
Merge multiple Zips into one @param string $output_zip_file Destination zip @param bool $separate (optional) If true (default), files will be placed in different directories @return bool @throws ZipException
entailment
public function add($file_name_or_array, bool $flatten_root_folder = false): ZipManager { try { foreach ( $this->zip_archives as $archive ) { $archive->add($file_name_or_array, $flatten_root_folder); } return $this; } catch (ZipException $ze) { throw $ze; } }
Add a file to all registered Zips @param mixed $file_name_or_array The filename to add or an array of filenames @param bool $flatten_root_folder (optional) If true, the Zip root folder will be flattened (default: false) @return ZipManager @throws ZipException
entailment
public function delete($file_name_or_array): ZipManager { try { foreach ( $this->zip_archives as $archive ) { $archive->delete($file_name_or_array); } return $this; } catch (ZipException $ze) { throw $ze; } }
Delete a file from any registered Zip @param mixed $file_name_or_array The filename to add or an array of filenames @return ZipManager @throws ZipException
entailment
public function close(): bool { try { foreach ( $this->zip_archives as $archive ) { $archive->close(); } return true; } catch (ZipException $ze) { throw $ze; } }
Close all Zips @return bool @throws ZipException
entailment
public static function getFormat($type, array $options = array()) { // Sanitize format type. $type = strtolower(preg_replace('/[^A-Z0-9_]/i', '', $type)); /* * Only instantiate the object if it doesn't already exist. * @deprecated 2.0 Object caching will no longer be supported, a new instance will be returned every time */ if (!isset(self::$formatInstances[$type])) { $localNamespace = __NAMESPACE__ . '\\Format'; $namespace = isset($options['format_namespace']) ? $options['format_namespace'] : $localNamespace; $class = $namespace . '\\' . ucfirst($type); if (!class_exists($class)) { // Were we given a custom namespace? If not, there's nothing else we can do if ($namespace === $localNamespace) { throw new \InvalidArgumentException(sprintf('Unable to load format class for type "%s".', $type), 500); } $class = $localNamespace . '\\' . ucfirst($type); if (!class_exists($class)) { throw new \InvalidArgumentException(sprintf('Unable to load format class for type "%s".', $type), 500); } } self::$formatInstances[$type] = new $class; } return self::$formatInstances[$type]; }
Returns an AbstractRegistryFormat object, only creating it if it doesn't already exist. @param string $type The format to load @param array $options Additional options to configure the object @return FormatInterface Registry format handler @since 1.5.0 @throws \InvalidArgumentException
entailment
public function search($name, $type = null, $deepSearch = true) { /** @var TokenInterface[] $array */ $array = $this->getArrayCopy(); foreach ($array as $token) { if (fnmatch($name, $token->getName())) { if ($type === null) { return $token; } if ($token->getTokenType() === $type) { return $token; } } if ($token instanceof Block && $token->hasChildren() && $deepSearch) { if ($res = $this->deepSearch($token, $name, $type)) { return $res; } } } return null; }
Search this object for a Token with a specific name and return the first match @param string $name [required] Name of the token @param int $type [optional] TOKEN_DIRECTIVE | TOKEN_BLOCK @param bool $deepSearch [optional] If the search should be multidimensional. Default is true @return null|TokenInterface Returns the Token or null if none is found
entailment
public function getIndex($name, $type = null) { /** @var TokenInterface[] $array */ $array = $this->getArrayCopy(); foreach ($array as $index => $token) { if ($token->getName() === $name) { if ($type === null) { return $index; } if ($token->getTokenType() === $type) { return $index; } } } return null; }
Search this object for a Token with specific name and return the index(key) of the first match @param string $name [required] Name of the token @param int $type [optional] TOKEN_DIRECTIVE | TOKEN_BLOCK @return int|null Returns the index or null if Token is not found
entailment
public function jsonSerialize() { /** @var \Tivie\HtaccessParser\Token\TokenInterface[] $array */ $array = $this->getArrayCopy(); $otp = array(); foreach ($array as $arr) { if (!$arr instanceof WhiteLine & !$arr instanceof Comment) { $otp[$arr->getName()] = $arr; } } return $otp; }
Get a representation ready to be encoded with json_encoded. Note: Whitelines and Comments are ignored and will not be included in the serialization @api @link http://php.net/manual/en/jsonserializable.jsonserialize.php @return mixed data which can be serialized by <b>json_encode</b>, which is a value of any type other than a resource.
entailment
public function txtSerialize($indentation = null, $ignoreWhiteLines = null, $ignoreComments = false) { /** @var \Tivie\HtaccessParser\Token\TokenInterface[] $array */ $array = $this->getArrayCopy(); $otp = ''; $this->indentation = (is_null($indentation)) ? $this->indentation : $indentation; $ignoreWhiteLines = (is_null($ignoreWhiteLines)) ? $this->ignoreWhiteLines : $ignoreWhiteLines; $ignoreComments = (is_null($ignoreComments)) ? $this->ignoreCommentss : $ignoreComments; foreach ($array as $num => $token) { $otp .= $this->txtSerializeToken($token, 0, !!$ignoreWhiteLines, !!$ignoreComments); } // remove whitelines at the end $otp = rtrim($otp); // and add an empty newline $otp .= PHP_EOL; return $otp; }
Returns a representation of the htaccess, ready for inclusion in a file @api @param int $indentation [optional] Defaults to null @param bool $ignoreWhiteLines [optional] Defaults to null @param bool $ignoreComments [optional] Defaults to null @return string
entailment
public function slice($offset, $length = null, $preserveKeys = false, $asArray = false) { if (!is_int($offset)) { throw new InvalidArgumentException('integer', 0); } if (!is_null($length) && !is_int($length)) { throw new InvalidArgumentException('integer', 1); } $preserveKeys = !!$preserveKeys; $array = $this->getArrayCopy(); $newArray = array_slice($array, $offset, $length, $preserveKeys); return (!!$asArray) ? $newArray : new self($newArray); }
Returns the sequence of elements as specified by the offset and length parameters. @param int $offset [required] If offset is non-negative, the sequence will start at that offset. If offset is negative, the sequence will start that far from the end of the array. @param int $length [optional] If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array. @param bool $preserveKeys [optional] Note that arraySlice() will reorder and reset the numeric array indices by default. You can change this behaviour by setting preserveKeys to TRUE. @param bool $asArray [optional] By default, slice() returns a new instance of HtaccessContainer object. If you prefer a basic array instead, set asArray to true @return array Returns the slice. @throws InvalidArgumentException
entailment
public function insertAt($offset, TokenInterface $token) { if (!is_int($offset)) { throw new InvalidArgumentException('integer', 0); } $this->splice($offset, 0, array($token)); return $this; }
@param int $offset [required] If offset is positive then the token will be inserted at that offset from the beginning. If offset is negative then it starts that far from the end of the input array. @param TokenInterface $token [required] The token to insert @return $this @throws InvalidArgumentException
entailment
public function splice($offset, $length = null, $replacement = array()) { if (!is_int($offset)) { throw new InvalidArgumentException('integer', 0); } if (!is_null($length) && !is_int($length)) { throw new InvalidArgumentException('integer', 1); } if (!is_array($replacement) && !$replacement instanceof \ArrayAccess) { throw new InvalidArgumentException('integer', 2); } $array = $this->getArrayCopy(); $spliced = array_splice($array, $offset, $length, $replacement); $this->exchangeArray($array); return $spliced; }
Removes the elements designated by offset and length, and replaces them with the elements of the replacement array, if supplied. @param int $offset [required] If offset is positive then the start of removed portion is at that offset from the beginning. If offset is negative then it starts that far from the end of the input array. @param int $length [optional] If length is omitted, removes everything from offset to the end. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length. @param array|\ArrayAccess $replacement [optional] If replacement array is specified, then the removed elements are replaced with elements from this array. @return array Returns the array consisting of the extracted elements. @throws InvalidArgumentException
entailment
public function findConcept($query, $options) { $query->where([ $this->config('field') => $this->config('states.concept'), ]); return $query; }
findConcept Finder for the state 'concepts'. @param \Cake\ORM\Query $query The current Query object. @param array $options Optional options. @return \Cake\ORM\Query The modified Query object.
entailment
public function findActive($query, $options) { $query->where([ $this->config('field') => $this->config('states.active'), ]); return $query; }
findActive Finder for the state 'active'. @param \Cake\ORM\Query $query The current Query object. @param array $options Optional options. @return \Cake\ORM\Query The modified Query object.
entailment
public function findDeleted($query, $options) { $query->where([ $this->config('field') => $this->config('states.deleted'), ]); return $query; }
findDeleted Finder for the state 'deleted'. @param \Cake\ORM\Query $query The current Query object. @param array $options Optional options. @return \Cake\ORM\Query The modified Query object.
entailment
public function getAnchor() { $linkedElement = $this->LinkedElement(); if ($linkedElement && $linkedElement->exists()) { return $linkedElement->getAnchor(); } return 'e' . $this->ID; }
Get a unique anchor name. @return string
entailment
public function forTemplate($holder = true) { if ($linked = $this->LinkedElement()) { return $linked->forTemplate($holder); } return null; }
Override to render template based on LinkedElement @return string|null HTML
entailment
private static function doReduce($reducedMetrics, $metric) { $metricLength = strlen($metric); $lastReducedMetric = count($reducedMetrics) > 0 ? end($reducedMetrics) : null; if ($metricLength >= self::MAX_UDP_SIZE_STR || null === $lastReducedMetric || strlen($newMetric = $lastReducedMetric . "\n" . $metric) > self::MAX_UDP_SIZE_STR ) { $reducedMetrics[] = $metric; } else { array_pop($reducedMetrics); $reducedMetrics[] = $newMetric; } return $reducedMetrics; }
This function reduces the number of packets,the reduced has the maximum dimension of self::MAX_UDP_SIZE_STR Reference: https://github.com/etsy/statsd/blob/master/README.md All metrics can also be batch send in a single UDP packet, separated by a newline character. @param array $reducedMetrics @param array $metric @return array
entailment
public function appendSampleRate($data, $sampleRate = 1) { if ($sampleRate < 1) { array_walk($data, function(&$message, $key) use ($sampleRate) { $message = sprintf('%s|@%s', $message, $sampleRate); }); } return $data; }
Reference: https://github.com/etsy/statsd/blob/master/README.md Sampling 0.1 Tells StatsD that this counter is being sent sampled every 1/10th of the time. @param mixed $data @param int $sampleRate @return mixed $data
entailment
public function send($data, $sampleRate = 1) { // check format if ($data instanceof StatsdDataInterface || is_string($data)) { $data = array($data); } if (!is_array($data) || empty($data)) { return; } // add sampling if ($sampleRate < 1) { $data = $this->appendSampleRate($data, $sampleRate); } // reduce number of packets if ($this->getReducePacket()) { $data = $this->reduceCount($data); } //failures in any of this should be silently ignored if .. try { $fp = $this->getSender()->open(); if (!$fp) { return; } $written = 0; foreach ($data as $key => $message) { $written += $this->getSender()->write($fp, $message); } $this->getSender()->close($fp); } catch (\Exception $e) { $this->throwException($e); } return $written; }
/* Send the metrics over UDP {@inheritDoc}
entailment
public function setMask(int $mask): ZipInterface { $mask = filter_var($mask, FILTER_VALIDATE_INT, [ "options" => [ "max_range" => 0777, "default" => 0777 ], 'flags' => FILTER_FLAG_ALLOW_OCTAL ]); $this->mask = $mask; return $this; }
Set the mask of the extraction folder @param int $mask Integer representation of the file mask @return Zip
entailment
public function setPassword(string $password): ZipInterface { $this->password = $password; $this->getArchive()->setPassword($password); return $this; }
Set zip password @param string $password @return Zip
entailment
public function getManipulatedData(GridField $gridField, SS_List $dataList) { if (!$gridField->State->GridFieldAddRelation) { return $dataList; } $objectID = Convert::raw2sql($gridField->State->GridFieldAddRelation); if ($objectID) { $object = DataObject::get_by_id($dataList->dataclass(), $objectID); if ($object) { // if the object is currently not linked to either a page or another list then we want to link to // the original, otherwise link to a clone if (!$object->ParentID) { $dataList->add($object); } else { $virtual = ElementVirtual::create(); $virtual->LinkedElementID = $object->ID; $virtual->write(); $dataList->add($virtual); } } } $gridField->State->GridFieldAddRelation = null; return $dataList; }
If an object ID is set, add the object to the list @param GridField $gridField @param SS_List $dataList @return SS_List
entailment
public function setCol($col = null) { if ($col !== null) { $this->otherOptions['col'] = $col; } else { unset($this->otherOptions['col']); } return $this; }
Name of the collection (Crawlbot or Bulk API job name) to search. By default the search will operate on all of your token's collections. @param null|string $col @return $this
entailment
public function setNum($num = 20) { if (!is_numeric($num) && $num !== self::SEARCH_ALL) { throw new \InvalidArgumentException( 'Argument can only be numeric or "all" to return all results.' ); } $this->otherOptions['num'] = $num; return $this; }
Number of results to return. Default is 20. To return all results in the search, pass num=all. @param int $num @return $this
entailment
public function buildUrl() { $url = rtrim($this->apiUrl, '/') . '?'; // Add token $url .= 'token=' . $this->diffbot->getToken(); // Add query $url .= '&query=' . urlencode($this->query); // Add other options foreach ($this->otherOptions as $option => $value) { $url .= '&' . $option . '=' . $value; } return $url; }
Builds out the URL string that gets requested once `call()` is called @return string
entailment
public function call($info = false) { if (!$info) { $ei = parent::call(); set_error_handler(function() { /* ignore errors */ }); $arr = json_decode((string)$ei->getResponse()->getBody(), true, 512, 1); restore_error_handler(); unset($arr['request']); unset($arr['objects']); $this->info = new SearchInfo($arr); return $ei; } if ($info && !$this->info) { $this->call(); } return $this->info; }
If you pass in `true`, you get back a SearchInfo object related to the last call. Keep in mind that passing in true before calling a default call() will implicitly call the call(), and then get the SearchInfo. So: $searchApi->call() // gets entities $searchApi->call(true) // gets SearchInfo about the executed query @todo: remove error avoidance when issue 12 is fixed: https://github.com/Swader/diffbot-php-client/issues/12 @param bool $info @return EntityIterator|SearchInfo
entailment
public function isOwnedBy($item, $user = []) { if (!is_array($item)) { $item = $item->toArray(); } if (empty($user)) { return false; } $itemUserId = $item[$this->config('column')]; $userId = $user['id']; if ($itemUserId === $userId) { return true; } return false; }
isOwnedBy @param array|\Cake\ORM\Entity $item Entity or array with the object to check on. @param array $user The user who is owner (or not). @return bool
entailment
public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) { // ensure statement has a ParameterContainer $parameterContainer = $statementContainer->getParameterContainer(); if (!$parameterContainer instanceof ParameterContainer) { $parameterContainer = new ParameterContainer(); $statementContainer->setParameterContainer($parameterContainer); } $sqls = []; $sqls[self::SHOW] = sprintf($this->specifications[static::SHOW], $this->show); $likePart = $this->processLike($adapter->getPlatform(), $adapter->getDriver(), $parameterContainer); if (is_array($likePart)) { $sqls[self::LIKE] = $this->createSqlFromSpecificationAndParameters( $this->specifications[static::LIKE], $likePart ); } $sql = implode(' ', $sqls); $statementContainer->setSql($sql); return; }
Prepare statement @param AdapterInterface $adapter @param StatementContainerInterface $statementContainer @return void
entailment
public function getSqlString(PlatformInterface $adapterPlatform = null) { // get platform, or create default $adapterPlatform = ($adapterPlatform) ? : new SphinxQL(); $sqls = []; $sqls[self::SHOW] = sprintf($this->specifications[static::SHOW], $this->show); $likePart = $this->processLike($adapterPlatform); if (is_array($likePart)) { $sqls[self::LIKE] = $this->createSqlFromSpecificationAndParameters( $this->specifications[static::LIKE], $likePart ); } $sql = implode(' ', $sqls); return $sql; }
Get SQL string for statement @param null|PlatformInterface $adapterPlatform If null, defaults to SphinxQL @return string
entailment
public function objectToString($object, $options = array()) { $array = json_decode(json_encode($object), true); return $this->dumper->dump($array, 2, 0); }
Converts an object into a YAML formatted string. We use json_* to convert the passed object to an array. @param object $object Data source object. @param array $options Options used by the formatter. @return string YAML formatted string. @since 1.0
entailment
public function updateCMSFields(FieldList $fields) { $global = $fields->dataFieldByName('AvailableGlobally'); if ($global) { $fields->removeByName('AvailableGlobally'); $fields->addFieldToTab('Root.Settings', $global); } if ($virtual = $fields->dataFieldByName('VirtualClones')) { if ($this->owner->VirtualClones()->Count() > 0) { $tab = $fields->findOrMakeTab('Root.VirtualClones'); $tab->setTitle(_t(__CLASS__ . '.LinkedTo', 'Linked To')); if ($ownerPage = $this->owner->getPage()) { $fields->addFieldToTab( 'Root.VirtualClones', LiteralField::create( 'DisplaysOnPage', sprintf( "<p>" . _t(__CLASS__ . '.OriginalContentFrom', 'The original content element appears on') . " <a href='%s'>%s</a></p>", ($ownerPage->hasMethod('CMSEditLink') && $ownerPage->canEdit()) ? $ownerPage->CMSEditLink() : $ownerPage->Link(), $ownerPage->MenuTitle ) ), 'VirtualClones' ); } $virtual->setConfig(new GridFieldConfig_Base()); $virtual ->setTitle(_t(__CLASS__ . '.OtherPages', 'Other pages')) ->getConfig() ->removeComponentsByType(GridFieldAddExistingAutocompleter::class) ->removeComponentsByType(GridFieldAddNewButton::class) ->removeComponentsByType(GridFieldDeleteAction::class) ->removeComponentsByType(GridFieldDetailForm::class) ->addComponent(new ElementalGridFieldDeleteAction()); $virtual->getConfig() ->getComponentByType(GridFieldDataColumns::class) ->setDisplayFields([ 'getPage.Title' => _t(__CLASS__ . '.GridFieldTitle', 'Title'), 'ParentCMSEditLink' => _t(__CLASS__ . '.GridFieldUsedOn', 'Used on'), ]); } else { $fields->removeByName('VirtualClones'); } } }
@param FieldList $fields @return FieldList
entailment
public function onBeforeDelete() { if (Versioned::get_reading_mode() == 'Stage.Stage') { $firstVirtual = false; $allVirtual = $this->getVirtualElements(); if ($this->getPublishedVirtualElements()->Count() > 0) { // choose the first one $firstVirtual = $this->getPublishedVirtualElements()->First(); $wasPublished = true; } elseif ($allVirtual->Count() > 0) { // choose the first one $firstVirtual = $this->getVirtualElements()->First(); $wasPublished = false; } if ($firstVirtual) { $clone = $this->owner->duplicate(false); // set clones values to first virtual's values $clone->ParentID = $firstVirtual->ParentID; $clone->Sort = $firstVirtual->Sort; $clone->write(); if ($wasPublished) { $clone->doPublish(); $firstVirtual->doUnpublish(); } // clone has a new ID, so need to repoint // all the other virtual elements foreach ($allVirtual as $virtual) { if ($virtual->ID == $firstVirtual->ID) { continue; } $pub = false; if ($virtual->isPublished()) { $pub = true; } $virtual->LinkedElementID = $clone->ID; $virtual->write(); if ($pub) { $virtual->doPublish(); } } $firstVirtual->delete(); } } }
Ensure that if there are elements that are virtualised from this element that we move the original element to replace one of the virtual elements But only if it's a delete not an unpublish
entailment
public function getUsage() { $usage = new ArrayList(); if ($page = $this->getPage()) { $usage->push($page); if ($this->virtualOwner) { $page->setField('ElementType', 'Linked'); } else { $page->setField('ElementType', 'Master'); } } $linkedElements = ElementVirtual::get()->filter('LinkedElementID', $this->ID); foreach ($linkedElements as $element) { $area = $element->Parent(); if ($area instanceof ElementalArea && $page = $area->getOwnerPage()) { $page->setField('ElementType', 'Linked'); $usage->push($page); } } $usage->removeDuplicates(); return $usage; }
get all pages where this element is used @return ArrayList
entailment
public function search($params) { $query = Model::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ 'menu_id' => $this->menuId, ]); $query->andFilterWhere(['like', 'menu', $this->menu]); return $dataProvider; }
Creates data provider instance with search query applied @param array $params @return ActiveDataProvider
entailment
public function initialize(array $config) { parent::initialize($config); $this->Controller = $this->_registry->getController(); $this->_addFromConfigure(); // set up the default helper $this->Controller->helpers['Utils.Menu'] = []; }
initialize Initialize callback for Components. @param array $config Configurations. @return void
entailment
public function beforeFilter($event) { $this->setController($event->subject()); if (method_exists($this->Controller, 'initMenuItems')) { $this->Controller->initMenuItems($event); } }
BeforeFilter Event This method will check if the `initMenuItems`-method exists in the `AppController`. That method contains menu-items to add. @param \Cake\Event\Event $event Event. @return void
entailment
public function area($area = null) { if ($area !== null) { $this->area = $area; } return $this->area; }
area Method to set or get the current area. Leave empty to get the current area. Set with a string to set a new area. @param string|void $area The area where the item should be stored. @return string
entailment
public function active($id) { $menu = $this->getMenu($this->area()); foreach ($menu as $key => $item) { if ($menu[$key]['id'] == $id) { $menu[$key]['active'] = true; } } $data = self::$data; $data[$this->area] = $menu; self::$data = $data; }
active Makes a menu item default active. ### Example: $this->Menu->active('bookmarks'); In this example the menu-item with the id `bookmarks` will be set to active. @param string $id The id of the menu-item @return void
entailment
public function getMenu($area = null) { if (!key_exists($area, self::$data)) { return self::$data; } else { return self::$data[$area]; } }
getMenu Returns the menu-data of a specific area, or full data if area is not set. @param string $area The area where the item should be stored. @return array The menu-items of the area.
entailment
public function add($title, $item = []) { $list = self::$data; $_item = [ 'id' => $title, 'parent' => false, 'url' => '#', 'title' => $title, 'icon' => '', 'area' => $this->area(), 'active' => false, 'weight' => 10, 'children' => [] ]; $item = array_merge($_item, $item); $url = Router::url($item['url']); $actives = $this->config('active'); if ($url === Router::url("/" . $this->Controller->request->url)) { $item['active'] = true; } $this->area = $item['area']; $data = self::$data; if (array_key_exists($this->area, $data)) { $menu = $data[$this->area]; } else { $menu = []; } if ($item['parent']) { if (array_key_exists($item['parent'], $menu)) { $menu[$item['parent']]['children'][$item['id']] = $item; } } else { $menu[$item['id']] = $item; } $menu = Hash::sort($menu, '{s}.weight', 'asc'); $data[$this->area] = $menu; self::$data = $data; }
add Adds a new menu-item. ### OPTIONS - id - parent - url - title - icon - area - weight @param string $title The title or id of the item. @param array $item Options for the item. @return void
entailment
public function remove($id, $options = []) { $_options = [ 'area' => false, ]; $options = array_merge($_options, $options); if ($options['area']) { $this->area = $item['area']; } unset(self::$data[$this->area][$id]); }
remove Removes a menu-item. ### OPTIONS - area The area to remove from. @param string $id Identifier of the item. @param array $options Options. @return void
entailment
protected function _addFromConfigure() { $configure = Configure::read('Menu.Register'); if (!is_array($configure)) { $configure = []; } foreach ($configure as $key => $item) { $this->add($key, $item); } }
_registerFromConfigure This method gets the menuitems from the Configure: `PostTypes.register.*`. ### Adding menuitems via the `Configure`-class You can add a menuitem by: `Configure::write('Menu.Register.MyName', [*settings*]);` @return void
entailment
public function produceStatsdData($key, $value = 1, $metric = StatsdDataInterface::STATSD_METRIC_COUNT) { $statsdData = $this->produceStatsdDataEntity(); if (null !== $key) { $statsdData->setKey($key); } if (null !== $value) { $statsdData->setValue($value); } if (null !== $metric) { $statsdData->setMetric($metric); } return $statsdData; }
{@inheritDoc}
entailment
protected function bindParametersFromContainer() { if ($this->parametersBound) { return; } $parameters = $this->parameterContainer->getNamedArray(); foreach ($parameters as $name => &$value) { // if param has no errata, PDO will detect the right type $type = null; if ($this->parameterContainer->offsetHasErrata($name)) { switch ($this->parameterContainer->offsetGetErrata($name)) { case ParameterContainer::TYPE_INTEGER: $type = \PDO::PARAM_INT; break; case ParameterContainer::TYPE_NULL: $type = \PDO::PARAM_NULL; break; case ParameterContainer::TYPE_DOUBLE: $value = (float)$value; break; case ParameterContainer::TYPE_LOB: $type = \PDO::PARAM_LOB; break; } } // Parameter is named or positional, value is reference $parameter = is_int($name) ? ($name + 1) : $name; $this->resource->bindParam($parameter, $value, $type); } }
Bind parameters from container
entailment
public function release( $version = 'dev-master' ) { $package = "youzanyun/open-sdk"; list( $vendor, $name ) = explode( '/', $package ); if ( empty( $vendor ) || empty( $name ) ) { return; } $this->_mkdir( 'release' ); $this->taskExec( "composer create-project {$package} {$name} {$version}" ) ->dir( __DIR__ . '/release' ) ->arg( '--prefer-dist' ) ->arg( '--no-dev' ) ->run(); $this->taskExec( 'composer remove composer/installers --update-no-dev' ) ->dir( __DIR__ . "/release/{$name}" ) ->run(); $this->taskExec( 'composer dump-autoload --optimize' ) ->dir( __DIR__ . "/release/{$name}" ) ->run(); $zipFile = "release/{$vendor}-{$name}.zip"; $this->_remove( $zipFile ); $this->taskPack( $zipFile ) ->addDir( $name, "release/{$name}" ) ->run(); if ( ! empty( $name ) ) { $this->_deleteDir( "release/{$name}" ); } }
Creates release zip @param string $version Version to build.
entailment
public static function get(int $code): string { if ( array_key_exists($code, self::ZIP_STATUS_CODES) ) return self::ZIP_STATUS_CODES[$code]; else return sprintf('Unknown status %s', $code); }
Get status from zip status code @param int $code ZIP status code @return string
entailment
public function getDate() { if (!isset($this->data['date'])) { return null; } try { return (class_exists('\Carbon\Carbon')) ? new \Carbon\Carbon($this->data['date'], 'GMT') : $this->data['date']; } catch (\Exception $e) { return null; } }
Returns date as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 Example date: "Wed, 18 Dec 2013 00:00:00 GMT" This will be a Carbon (https://github.com/briannesbitt/Carbon) instance if Carbon is installed. @return \Carbon\Carbon | string
entailment
public function getEstimatedDate() { $date = $this->getOrDefault('estimatedDate', $this->getDate()); return (class_exists('\Carbon\Carbon')) ? new \Carbon\Carbon($date, 'GMT') : $date; }
If an article's date is ambiguous, Diffbot will attempt to estimate a more specific timestamp using various factors. This will not be generated for articles older than two days, or articles without an identified date. @see Article::getDate() - used when estimatedDate isn't defined This will be a Carbon (https://github.com/briannesbitt/Carbon) instance if Carbon is installed. @return \Carbon\Carbon | string
entailment
public function from($table) { if ($table instanceof TableIdentifier) { $table = $table->getTable(); // Ignore schema because it is not supported by SphinxQL } $this->table = $table; return $this; }
Create from statement @param string|TableIdentifier $table @return Delete
entailment
public function getDownloadUrl($type = "json") { switch ($type) { case "json": return $this->data['downloadJson']; case "debug": return $this->data['downloadUrls']; case "csv": return rtrim($this->data['downloadJson'], '.json') . '.csv'; default: break; } throw new \InvalidArgumentException( 'Only json, debug, or csv download link available. You asked for: ' . $type); }
Returns the link to the dataset the job produced. Accepted arguments are: "json", "csv" and "debug". It is important to be aware of the difference between the types. See "Retrieving Bulk Data" in link. @see https://www.diffbot.com/dev/docs/crawl/api.jsp @param string $type @return string @throws DiffbotException
entailment
public function setPath(?string $path = null): ZipInterface { if ( $path === null ) { $this->path = null; } else if ( !file_exists($path) ) { throw new ZipException("Not existent path: $path"); } else { $this->path = $path; } return $this; }
Set current base path (to add relative files to zip archive) @param string|null $path @return Zip @throws ZipException
entailment
public function setText($text) { if (!is_string($text)) { throw new InvalidArgumentException('string', 0); } $text = trim($text); if (strpos($text, '#') !== 0) { $text = '# ' . $text; } $this->text = $text; return $this; }
Set the Comment Text @param string $text The comment new text. A # will be prepended automatically if it isn't found at the beginning of the string. @return $this @throws InvalidArgumentException
entailment
public function setSeeds(array $seeds) { $invalidSeeds = []; foreach ($seeds as $seed) { if (!filter_var($seed, FILTER_VALIDATE_URL)) { $invalidSeeds[] = $seed; } } if (!empty($invalidSeeds)) { throw new \InvalidArgumentException( 'Some seeds were invalid: ' . implode(',', $invalidSeeds) ); } $this->seeds = $seeds; return $this; }
An array of URLs (seeds) which to crawl for matching links By default Crawlbot will restrict spidering to the entire domain ("http://blog.diffbot.com" will include URLs at "http://www.diffbot.com"). @param array $seeds @return $this
entailment
public function setUrlCrawlPatterns(array $pattern = null) { $this->otherOptions['urlCrawlPattern'] = ($pattern === null) ? null : implode("||", array_map(function ($item) { return urlencode($item); }, $pattern)); return $this; }
Array of strings to limit pages crawled to those whose URLs contain any of the content strings. You can use the exclamation point to specify a negative string, e.g. !product to exclude URLs containing the string "product," and the ^ and $ characters to limit matches to the beginning or end of the URL. The use of a urlCrawlPattern will allow Crawlbot to spider outside of the seed domain; it will follow all matching URLs regardless of domain. @param array $pattern @return $this
entailment
public function setPageProcessPatterns(array $pattern) { $this->otherOptions['pageProcessPattern'] = implode("||", array_map(function ($item) { return urlencode($item); }, $pattern)); return $this; }
Specify ||-separated strings to limit pages processed to those whose HTML contains any of the content strings. @param array $pattern @return $this
entailment
public function setMaxHops($input = -1) { if ((int)$input < -1) { $input = -1; } $this->otherOptions['maxHops'] = (int)$input; return $this; }
Specify the depth of your crawl. A maxHops=0 will limit processing to the seed URL(s) only -- no other links will be processed; maxHops=1 will process all (otherwise matching) pages whose links appear on seed URL(s); maxHops=2 will process pages whose links appear on those pages; and so on By default, Crawlbot will crawl and process links at any depth. @param int $input @return $this
entailment
public function setMaxToCrawl($input = 100000) { if ((int)$input < 1) { $input = 1; } $this->otherOptions['maxToCrawl'] = (int)$input; return $this; }
Specify max pages to spider. Default: 100,000. @param int $input @return $this
entailment
public function setMaxToProcess($input = 100000) { if ((int)$input < 1) { $input = 1; } $this->otherOptions['maxToProcess'] = (int)$input; return $this; }
Specify max pages to process through Diffbot APIs. Default: 100,000. @param int $input @return $this
entailment
public function notify($string) { if (filter_var($string, FILTER_VALIDATE_EMAIL)) { $this->otherOptions['notifyEmail'] = $string; return $this; } if (filter_var($string, FILTER_VALIDATE_URL)) { $this->otherOptions['notifyWebhook'] = urlencode($string); return $this; } throw new InvalidArgumentException( 'Only valid email or URL accepted! You provided: ' . $string ); }
If input is email address, end a message to this email address when the crawl hits the maxToCrawl or maxToProcess limit, or when the crawl completes. If input is URL, you will receive a POST with X-Crawl-Name and X-Crawl-Status in the headers, and the full JSON response in the POST body. @param string $string @return $this @throws InvalidArgumentException
entailment
public function setCrawlDelay($input = 0.25) { if (!is_numeric($input)) { throw new InvalidArgumentException('Input must be numeric.'); } $input = ($input < 0) ? 0.25 : $input; $this->otherOptions['crawlDelay'] = (float)$input; return $this; }
Wait this many seconds between each URL crawled from a single IP address. Specify the number of seconds as an integer or floating-point number. @param float $input @return $this @throws InvalidArgumentException
entailment
public function setRepeat($input) { if (!is_numeric($input) || !$input) { throw new \InvalidArgumentException('Only positive numbers allowed.'); } $this->otherOptions['repeat'] = (float)$input; return $this; }
Specify the number of days as a floating-point (e.g. repeat=7.0) to repeat this crawl. By default crawls will not be repeated. @param int|float $input @return $this @throws \InvalidArgumentException
entailment
public function setMaxRounds($input = 0) { if ((int)$input < -1) { $input = -1; } $this->otherOptions['maxRounds'] = (int)$input; return $this; }
Specify the maximum number of crawl repeats. By default (maxRounds=0) repeating crawls will continue indefinitely. @param int $input @return $this
entailment
public function buildUrl() { if (isset($this->otherOptions['urlProcessRegEx']) && !empty($this->otherOptions['urlProcessRegEx']) ) { unset($this->otherOptions['urlProcessPattern']); } if (isset($this->otherOptions['urlCrawlRegEx']) && !empty($this->otherOptions['urlCrawlRegEx']) ) { unset($this->otherOptions['urlCrawlPattern']); } // Add token $url = 'token=' . $this->diffbot->getToken(); if ($this->getName()) { // Add name $url .= '&name=' . $this->getName(); // Add seeds if (!empty($this->seeds)) { $url .= '&seeds=' . implode('%20', array_map(function ($item) { return urlencode($item); }, $this->seeds)); } // Add other options if (!empty($this->otherOptions)) { foreach ($this->otherOptions as $option => $value) { $url .= '&' . $option . '=' . $value; } } // Add API link $url .= '&apiUrl=' . $this->getApiString(); } return $url; }
Builds out the URL string that gets requested once `call()` is called @return string
entailment
public function getUrlReportUrl($num = null) { $this->otherOptions['type'] = 'urls'; if (!empty($num) && is_numeric($num)) { $this->otherOptions['num'] = $num; } // Setup data endpoint $url = $this->apiUrl . '/data'; // Add token $url .= '?token=' . $this->diffbot->getToken(); if ($this->getName()) { // Add name $url .= '&name=' . $this->getName(); // Add other options if (!empty($this->otherOptions)) { foreach ($this->otherOptions as $option => $value) { $url .= '&' . $option . '=' . $value; } } } return $url; }
Sets the request type to "urls" to retrieve the URL Report URL for understanding diagnostic data of URLs @return $this
entailment
public function setHttpClient(Client $client = null) { if ($client === null) { $client = new Client( HttpClientDiscovery::find(), MessageFactoryDiscovery::find() ); } $this->client = $client; return $this; }
Sets the client to be used for querying the API endpoints @param Client $client @see http://php-http.readthedocs.org/en/latest/utils/#httpmethodsclient @return $this
entailment
public function setEntityFactory(EntityFactory $factory = null) { if ($factory === null) { $factory = new Entity(); } $this->factory = $factory; return $this; }
Sets the Entity Factory which will create the Entities from Responses @param EntityFactory $factory @return $this
entailment
public function createProductAPI($url) { $api = new Product($url); if (!$this->getHttpClient()) { $this->setHttpClient(); } if (!$this->getEntityFactory()) { $this->setEntityFactory(); } return $api->registerDiffbot($this); }
Creates a Product API interface @param string $url Url to analyze @return Product
entailment
public function createArticleAPI($url) { $api = new Article($url); if (!$this->getHttpClient()) { $this->setHttpClient(); } if (!$this->getEntityFactory()) { $this->setEntityFactory(); } return $api->registerDiffbot($this); }
Creates an Article API interface @param string $url Url to analyze @return Article
entailment
public function createImageAPI($url) { $api = new Image($url); if (!$this->getHttpClient()) { $this->setHttpClient(); } if (!$this->getEntityFactory()) { $this->setEntityFactory(); } return $api->registerDiffbot($this); }
Creates an Image API interface @param string $url Url to analyze @return Image
entailment
public function createAnalyzeAPI($url) { $api = new Analyze($url); if (!$this->getHttpClient()) { $this->setHttpClient(); } if (!$this->getEntityFactory()) { $this->setEntityFactory(); } return $api->registerDiffbot($this); }
Creates an Analyze API interface @param string $url Url to analyze @return Analyze
entailment
public function createDiscussionAPI($url) { $api = new Discussion($url); if (!$this->getHttpClient()) { $this->setHttpClient(); } if (!$this->getEntityFactory()) { $this->setEntityFactory(); } return $api->registerDiffbot($this); }
Creates an Discussion API interface @param string $url Url to analyze @return Discussion
entailment
public function createCustomAPI($url, $name) { $api = new Custom($url, $name); if (!$this->getHttpClient()) { $this->setHttpClient(); } if (!$this->getEntityFactory()) { $this->setEntityFactory(); } return $api->registerDiffbot($this); }
Creates a generic Custom API Does not have predefined Entity, so by default returns Wildcards @param string $url Url to analyze @param string $name Name of the custom API, required to finalize URL @return Custom
entailment
public function crawl($name = null, Api $api = null) { $api = new Crawl($name, $api); if (!$this->getHttpClient()) { $this->setHttpClient(); } if (!$this->getEntityFactory()) { $this->setEntityFactory(); } return $api->registerDiffbot($this); }
Creates a new Crawljob with the given name. @see https://www.diffbot.com/dev/docs/crawl/ @param string $name Name of the crawljob. Needs to be unique. @param Api $api Optional instance of an API - if omitted, must be set later manually @return Crawl
entailment
public function search($q) { $api = new Search($q); if (!$this->getHttpClient()) { $this->setHttpClient(); } if (!$this->getEntityFactory()) { $this->setEntityFactory(); } return $api->registerDiffbot($this); }
Search query. @see https://www.diffbot.com/dev/docs/search/#query @param string $q @return Search
entailment
public static function open(string $zip_file): ZipInterface { try { $zip = new Zip($zip_file); $zip->setArchive(self::openZipFile($zip_file)); } catch (ZipException $ze) { throw $ze; } return $zip; }
{@inheritdoc}
entailment
public static function check(string $zip_file): bool { try { $zip = self::openZipFile($zip_file, ZipArchive::CHECKCONS); $zip->close(); } catch (ZipException $ze) { throw $ze; } return true; }
{@inheritdoc}
entailment
public static function create(string $zip_file, bool $overwrite = false): ZipInterface { $overwrite = DataFilter::filterBoolean($overwrite); try { $zip = new Zip($zip_file); if ( $overwrite ) { $zip->setArchive( self::openZipFile( $zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ); } else { $zip->setArchive( self::openZipFile($zip_file, ZipArchive::CREATE) ); } } catch (ZipException $ze) { throw $ze; } return $zip; }
{@inheritdoc}
entailment
public function listFiles(): array { $list = []; for ( $i = 0; $i < $this->getArchive()->numFiles; $i++ ) { $name = $this->getArchive()->getNameIndex($i); if ( $name === false ) { throw new ZipException(StatusCodes::get($this->getArchive()->status)); } $list[] = $name; } return $list; }
{@inheritdoc}
entailment
public function extract(string $destination, $files = null): bool { if ( empty($destination) ) { throw new ZipException("Invalid destination path: $destination"); } if ( !file_exists($destination) ) { $omask = umask(0); $action = mkdir($destination, $this->getMask(), true); umask($omask); if ( $action === false ) { throw new ZipException("Error creating folder: $destination"); } } if ( !is_writable($destination) ) { throw new ZipException("Destination path $destination not writable"); } if ( is_array($files) && @sizeof($files) != 0 ) { $file_matrix = $files; } else { $file_matrix = $this->getArchiveFiles(); } if ( $this->getArchive()->extractTo($destination, $file_matrix) === false ) { throw new ZipException(StatusCodes::get($this->getArchive()->status)); } return true; }
{@inheritdoc}
entailment
public function add( $file_name_or_array, bool $flatten_root_folder = false, int $compression = self::CM_DEFAULT, int $encryption = self::EM_NONE ): ZipInterface { if ( empty($file_name_or_array) ) { throw new ZipException(StatusCodes::get(ZipArchive::ER_NOENT)); } if ( $encryption !== self::EM_NONE && $this->getPassword() === null ) { throw new ZipException("Cannot encrypt resource: no password set"); } $flatten_root_folder = DataFilter::filterBoolean($flatten_root_folder); try { if ( is_array($file_name_or_array) ) { foreach ( $file_name_or_array as $file_name ) { $this->addItem($file_name, $flatten_root_folder, $compression, $encryption); } } else { $this->addItem($file_name_or_array, $flatten_root_folder, $compression, $encryption); } } catch (ZipException $ze) { throw $ze; } return $this; }
{@inheritdoc}
entailment
public function delete($file_name_or_array): ZipInterface { if ( empty($file_name_or_array) ) { throw new ZipException(StatusCodes::get(ZipArchive::ER_NOENT)); } try { if ( is_array($file_name_or_array) ) { foreach ( $file_name_or_array as $file_name ) { $this->deleteItem($file_name); } } else { $this->deleteItem($file_name_or_array); } } catch (ZipException $ze) { throw $ze; } return $this; }
{@inheritdoc}
entailment
public function close(): bool { if ( $this->getArchive()->close() === false ) { throw new ZipException(StatusCodes::get($this->getArchive()->status)); } return true; }
{@inheritdoc}
entailment
private function getArchiveFiles(): array { $list = []; for ( $i = 0; $i < $this->getArchive()->numFiles; $i++ ) { $file = $this->getArchive()->statIndex($i); if ( $file === false ) { continue; } $name = str_replace('\\', '/', $file['name']); if ( ( $name[0] == "." && in_array($this->getSkipMode(), ["HIDDEN", "ALL"]) ) || ( $name[0] == "." && @$name[1] == "_" && in_array($this->getSkipMode(), ["COMODOJO", "ALL"]) ) ) { continue; } $list[] = $name; } return $list; }
Get a list of file contained in zip archive before extraction @return array
entailment
private function addItem( string $file, bool $flatroot = false, int $compression = self::CM_DEFAULT, int $encryption = self::EM_NONE, ?string $base = null ): void { $file = is_null($this->getPath()) ? $file : $this->getPath()."/$file"; $real_file = str_replace('\\', '/', realpath($file)); $real_name = basename($real_file); if ( $base !== null && ( ( $real_name[0] == "." && in_array($this->getSkipMode(), ["HIDDEN", "ALL"]) ) || ( $real_name[0] == "." && @$real_name[1] == "_" && in_array($this->getSkipMode(), ["COMODOJO", "ALL"]) ) ) ) { return; } if ( is_dir($real_file) ) { $this->addDirectoryItem($real_file, $real_name, $compression, $encryption, $base, $flatroot); } else { $this->addFileItem($real_file, $real_name, $compression, $encryption, $base); } }
Add item to zip archive @param string $file File to add (realpath) @param bool $flatroot (optional) If true, source directory will be not included @param string $base (optional) Base to record in zip file @return void @throws ZipException
entailment
private function deleteItem(string $file): void { if ( $this->getArchive()->deleteName($file) === false ) { throw new ZipException(StatusCodes::get($this->getArchive()->status)); } }
Delete item from zip archive @param string $file File to delete (zippath) @return void @throws ZipException
entailment
private static function openZipFile(string $zip_file, int $flags = null): ZipArchive { $zip = new ZipArchive(); $open = $zip->open($zip_file, $flags); if ( $open !== true ) { throw new ZipException(StatusCodes::get($open)); } return $zip; }
Open a zip file @param string $zip_file ZIP file name @param int $flags ZipArchive::open flags @return ZipArchive @throws ZipException
entailment
protected function _processAssociation(Event $event, EntityInterface $entity, Association $assoc, array $settings) { $foreignKeys = (array)$assoc->foreignKey(); $primaryKeys = (array)$assoc->bindingKey(); $countConditions = $entity->extract($foreignKeys); $updateConditions = array_combine($primaryKeys, $countConditions); $countOriginalConditions = $entity->extractOriginalChanged($foreignKeys); if ($countOriginalConditions !== []) { $updateOriginalConditions = array_combine($primaryKeys, $countOriginalConditions); } foreach ($settings as $field => $config) { if (is_int($field)) { $field = $config; $config = []; } if (!is_string($config) && is_callable($config)) { $count = $config($event, $entity, $this->_table, false, $countConditions); } else { $count = $this->_getCount($config, $countConditions); } $assoc->target()->updateAll([$field => $count], $updateConditions); if (isset($updateOriginalConditions)) { if (!is_string($config) && is_callable($config)) { $count = $config($event, $entity, $this->_table, true, $countOriginalConditions); } else { $count = $this->_getCount($config, $countOriginalConditions); } $assoc->target()->updateAll([$field => $count], $updateOriginalConditions); } } }
Updates sum cache for a single association @param \Cake\Event\Event $event Event instance. @param \Cake\Datasource\EntityInterface $entity Entity @param Association $assoc The association object @param array $settings The settings for sum cache for this association @return void
entailment
public function beforeSave(Event $event, Entity $entity) { $config = $this->_config; foreach ($config['fields'] as $field => $fieldOption) { $data = $entity->toArray(); $virtualField = $field . $config['suffix']; if (!isset($data[$virtualField]) || !is_array($data[$virtualField])) { continue; } $file = $entity->get($virtualField); $error = $this->_triggerErrors($file); if ($error === false) { continue; } elseif (is_string($error)) { throw new \ErrorException($error); } if (!isset($fieldOption['path'])) { throw new \LogicException(__('The path for the {0} field is required.', $field)); } if (isset($fieldOption['prefix']) && (is_bool($fieldOption['prefix']) || is_string($fieldOption['prefix']))) { $this->_prefix = $fieldOption['prefix']; } $extension = (new File($file['name'], false))->ext(); $uploadPath = $this->_getUploadPath($entity, $fieldOption['path'], $extension); if (!$uploadPath) { throw new \ErrorException(__('Error to get the uploadPath.')); } $folder = new Folder($this->_config['root']); $folder->create($this->_config['root'] . dirname($uploadPath)); if ($this->_moveFile($entity, $file['tmp_name'], $uploadPath, $field, $fieldOption)) { if (!$this->_prefix) { $this->_prefix = ''; } $entity->set($field, $this->_prefix . $uploadPath); } $entity->unsetProperty($virtualField); } }
Check if there is some files to upload and modify the entity before it is saved. At the end, for each files to upload, unset their "virtual" property. @param Event $event The beforeSave event that was fired. @param Entity $entity The entity that is going to be saved. @throws \LogicException When the path configuration is not set. @throws \ErrorException When the function to get the upload path failed. @return void
entailment
protected function _triggerErrors($file) { if (!empty($file['error'])) { switch ((int)$file['error']) { case UPLOAD_ERR_INI_SIZE: $message = __('The uploaded file exceeds the upload_max_filesize directive in php.ini : {0}', ini_get('upload_max_filesize')); break; case UPLOAD_ERR_FORM_SIZE: $message = __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'); break; case UPLOAD_ERR_NO_FILE: $message = false; break; case UPLOAD_ERR_PARTIAL: $message = __('The uploaded file was only partially uploaded.'); break; case UPLOAD_ERR_NO_TMP_DIR: $message = __('Missing a temporary folder.'); break; case UPLOAD_ERR_CANT_WRITE: $message = __('Failed to write file to disk.'); break; case UPLOAD_ERR_EXTENSION: $message = __('A PHP extension stopped the file upload.'); break; default: $message = __('Unknown upload error.'); } return $message; } }
Trigger upload errors. @param array $file The file to check. @return string|int|void
entailment
protected function _moveFile(Entity $entity, $source = false, $destination = false, $field = false, array $options = []) { if ($source === false || $destination === false || $field === false) { return false; } if (isset($options['overwrite']) && is_bool($options['overwrite'])) { $this->_overwrite = $options['overwrite']; } if ($this->_overwrite) { $this->_deleteOldUpload($entity, $field, $destination, $options); } $file = new File($source, false, 0755); if ($file->copy($this->_config['root'] . $destination, $this->_overwrite)) { return true; } return false; }
Move the temporary source file to the destination file. @param \Cake\ORM\Entity $entity The entity that is going to be saved. @param bool|string $source The temporary source file to copy. @param bool|string $destination The destination file to copy. @param bool|string $field The current field to process. @param array $options The configuration options defined by the user. @return bool
entailment
protected function _deleteOldUpload(Entity $entity, $field = false, $newFile = false, array $options = []) { if ($field === false || $newFile === false) { return true; } $fileInfo = pathinfo($entity->$field); $newFileInfo = pathinfo($newFile); if (isset($options['defaultFile']) && (is_bool($options['defaultFile']) || is_string($options['defaultFile']))) { $this->_defaultFile = $options['defaultFile']; } if ($fileInfo['basename'] == $newFileInfo['basename'] || $fileInfo['basename'] == pathinfo($this->_defaultFile)['basename']) { return true; } if ($this->_prefix) { $entity->$field = str_replace($this->_prefix, "", $entity->$field); } $file = new File($this->_config['root'] . $entity->$field, false); if ($file->exists()) { $file->delete(); return true; } return false; }
Delete the old upload file before to save the new file. We can not just rely on the copy file with the overwrite, because if you use an identifier like :md5 (Who use a different name for each file), the copy function will not delete the old file. @param \Cake\ORM\Entity $entity The entity that is going to be saved. @param bool|string $field The current field to process. @param bool|string $newFile The new file path. @param array $options The configuration options defined by the user. @return bool
entailment
protected function _getUploadPath(Entity $entity, $path = false, $extension = false) { if ($extension === false || $path === false) { return false; } $path = trim($path, DS); $identifiers = [ ':id' => $entity->id, ':md5' => md5(rand() . uniqid() . time()), ':y' => date('Y'), ':m' => date('m') ]; return strtr($path, $identifiers) . '.' . strtolower($extension); }
Get the path formatted without its identifiers to upload the file. Identifiers : :id : Id of the Entity. :md5 : A random and unique identifier with 32 characters. :y : Based on the current year. :m : Based on the current month. i.e : upload/:id/:md5 -> upload/2/5e3e0d0f163196cb9526d97be1b2ce26.jpg @param \Cake\ORM\Entity $entity The entity that is going to be saved. @param bool|string $path The path to upload the file with its identifiers. @param bool|string $extension The extension of the file. @return bool|string
entailment
public function beforeFind($event, $query, $options, $primary) { if ($this->config('contain')) { if ($this->config('created_by')) { $query->contain(['CreatedBy' => ['fields' => $this->config('fields')]]); } if ($this->config('modified_by')) { $query->contain(['ModifiedBy' => ['fields' => $this->config('fields')]]); } } }
BeforeFind callback Used to add CreatedBy and ModifiedBy to the contain of the query. @param \Cake\Event\Event $event Event. @param \Cake\ORM\Query $query The Query object. @param array $options Options. @param bool $primary Root Query or not. @return void
entailment
public function beforeSave($event, $entity, $options) { $auth = Configure::read('GlobalAuth'); $id = $auth['id']; if ($entity->isNew()) { if ($this->config('created_by')) { $entity->set($this->config('created_by'), $id); } } if ($this->config('modified_by')) { $entity->set($this->config('modified_by'), $id); } }
BeforeSave callback Used to add the user to the `created_by` and `modified_by` fields. @param \Cake\Event\Event $event Event. @param \Cake\ORM\Entity $entity The Entity to save on. @param array $options Options. @return void
entailment
public function getMessage($withMetric = true) { if (!$withMetric) { $result = sprintf('%s:%s', $this->getKey(), $this->getValue()); } else { $result = sprintf('%s:%s|%s', $this->getKey(), $this->getValue(), $this->getMetric()); } $sampleRate = $this->getSampleRate(); if($sampleRate < 1){ $result.= "|@$sampleRate"; } return $result; }
@param bool $withMetric @return string
entailment