sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function createView($options = []): View { $view = parent::createView($options); $templateVars = $view->getTemplateData(); $templateVars['data']['actions'] = $this->actionManager->createActionsViewData($this->createActions($options)); $view->setTemplateData($templateVars); ...
{@inheritdoc}
entailment
public function process(OrderInterface $order) { $shipment = $this->getOrderShipment($order); $this->calculate($shipment, $order); }
{@inheritdoc}
entailment
private function getOrderShipment(OrderInterface $order) { if ($order->getShipment()) { return $order->getShipment(); } /** @var ShipmentInterface $shipment */ $shipment = $this->shipmentFactory->createNew(); $order->setShipment($shipment); $shipment->set...
@param OrderInterface $order @throws UnresolvedDefaultShippingMethodException @return ShipmentInterface
entailment
public function resolveGroups($formType) { $formGroups = null; if (isset($this->formConfig[$formType]['default_groups'])) { $formGroups = $this->formConfig[$formType]['default_groups']; } if(is_array($formGroups)) { $groups = $formGroups; } else { ...
Return groups by form type @param string $formType @return Group[]
entailment
protected function write(array $record) { $chat_id = $this->bot->getChatLog(); // Check chat_id is valid if ($chat_id !== "") { $this->bot->withChatId($chat_id, 'sendMessage', $record['message']); } }
\brief Send the message to telegram chat @param array $record
entailment
public function clearLock($name) { if (!isset($this->locks[$name])) { return false; } unset($this->locks[$name]); return true; }
Clear lock without releasing it Do not use this method unless you know what you do @param string $name name of lock @return bool
entailment
public function submitAction(Request $request) { $name = $request->get('name'); /** @var RequestConfiguration $configuration */ $configuration = $this->requestConfigurationFactory->createSimple($request); $formConfiguration = $this->configurationFactory->create($name); $for...
@param Request $request @return JsonResponse
entailment
public function process(OrderInterface $order) { $items = $order->getItems(); foreach($items as $orderItem) { $this->processItem($orderItem); } }
{@inheritdoc}
entailment
public function load(array $config, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $config); $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $this->registerResources('enhavo_newsletter', $config['driver']...
{@inheritdoc}
entailment
public function acquireLock($name, $timeout = null) { $blocking = $timeout === null; $start = microtime(true); $end = $start + $timeout / 1000; $locked = false; while (!(empty($this->locks[$name]) && $locked = $this->getLock($name, $blocking)) && ($blocking || ($timeout > 0 &...
Acquire lock @param string $name name of lock @param null|int $timeout 1. null if you want blocking lock 2. 0 if you want just lock and go 3. $timeout > 0 if you want to wait for lock some time (in milliseconds) @return bool
entailment
public function dispatchPostEvent($eventName, RequestConfiguration $requestConfiguration, ResourceInterface $resource) { $eventName = $requestConfiguration->getEvent() ?: $eventName; $this->eventDispatcher->dispatch(sprintf('enhavo_app.post_%s', $eventName), new ResourceControllerEvent($resource)); ...
{@inheritdoc}
entailment
public function createView($options = []): View { $view = parent::createView($options); $templateVars = $view->getTemplateData(); if($options['tabs'] == null) { $tabs = [ 'main' => [ 'label' => '', 'template' => $options['f...
{@inheritdoc}
entailment
public function get($name, $registeredLockImplementorName = null) { if (null === $registeredLockImplementorName) { $registeredLockImplementorName = $this->getDefaultLockImplementorName(); } if (!isset($this->mutexes[$registeredLockImplementorName][$name])) { $this->c...
Create and/or get mutex @param string $name @param string $registeredLockImplementorName @return Mutex
entailment
protected function processMessage($message) { // Check if the message was forward isset($message['forward_from']) ? $index = 'forward_from' : $index = 'from'; $response = $this->prepareResponse($message[$index]); $this->sendMessage($response); }
get information about its author (if forwarded, its original author).
entailment
public function addCategory(\Enhavo\Bundle\CategoryBundle\Entity\Category $category) { $category->setCollection($this); $this->categories[] = $category; return $this; }
Add categories @param \Enhavo\Bundle\CategoryBundle\Entity\Category $categories @return Collection
entailment
public function removeCategory(\Enhavo\Bundle\CategoryBundle\Entity\Category $category) { $category->setCollection(null); $this->categories->removeElement($category); }
Remove categories @param \Enhavo\Bundle\CategoryBundle\Entity\Category $categories
entailment
protected function setAssoc($handle, $assoc) { $oldSession = session_id(); session_commit(); session_id($assoc['handle']); session_start(); $_SESSION['assoc'] = $assoc; session_commit(); if($oldSession) { session_id($oldSession); sessio...
Stores an association. If you want to use php sessions in your provider code, you have to replace it. @param String $handle Association handle -- should be used as a key. @param Array $assoc Association data.
entailment
protected function getAssoc($handle) { $oldSession = session_id(); session_commit(); session_id($handle); session_start(); $assoc = null; if(!empty($_SESSION['assoc'])) { $assoc = $_SESSION['assoc']; } session_commit(); if($oldSessi...
Retreives association data. If you want to use php sessions in your provider code, you have to replace it. @param String $handle Association handle. @return Array Association data.
entailment
protected function delAssoc($handle) { $oldSession = session_id(); session_commit(); session_id($handle); session_start(); session_destroy(); if($oldSession) { session_id($oldSession); session_start(); } }
Deletes an association. If you want to use php sessions in your provider code, you have to replace it. @param String $handle Association handle.
entailment
protected function shared_secret($hash) { $length = 20; if($hash == 'sha256') { $length = 256; } $secret = ''; for($i = 0; $i < $length; $i++) { $secret .= mt_rand(0,255); } return $secret; }
Generates a random shared secret. @return string
entailment
protected function keygen($length) { $key = ''; for($i = 1; $i < $length; $i++) { $key .= mt_rand(0,9); } $key .= mt_rand(1,9); return $key; }
Generates a private key. @param int $length Length of the key.
entailment
function xrds($force=null) { if($force) { echo $this->xrdsContent(); die(); } elseif($force === false) { header('X-XRDS-Location: '. $this->xrdsLocation); return; } if (isset($_GET['xrds']) || (isset($_SERVER['HTTP_...
Displays an XRDS document, or redirects to it. By default, it detects whether it should display or redirect automatically. @param bool|null $force When true, always display the document, when false always redirect.
entailment
protected function xrdsContent() { $lines = array( '<?xml version="1.0" encoding="UTF-8"?>', '<xrds:XRDS xmlns:xrds="xri://$xrds" xmlns="xri://$xrd*($v*2.0)">', '<XRD>', ' <Service>', ' <Type>' . $this->ns . '/' . ($this->select_id ? 'ser...
Returns the content of the XRDS document @return String The XRDS document.
entailment
function server() { if(isset($this->data['openid_assoc_handle'])) { $this->assoc = $this->getAssoc($this->data['openid_assoc_handle']); if(isset($this->assoc['data'])) { # We have additional data stored for setup. $this->data += $this->assoc['data']; ...
Does everything that a provider has to -- in one function.
entailment
protected function verify() { # Firstly, we need to make sure that there's an association. # Otherwise the verification will fail, # because we've signed assoc_handle in the assertion if(empty($this->assoc)) { return false; } # Next, we check tha...
Aids an RP in assertion verification. @return bool Information whether the verification suceeded.
entailment
protected function associate() { # Rejecting no-encryption without TLS. if(empty($_SERVER['HTTPS']) && $this->data['openid_session_type'] == 'no-encryption') { $this->directErrorResponse(); } # Checking whether we support DH at all. if (!$this->dh && subs...
Performs association with an RP.
entailment
protected function generateAssociation() { $this->assoc = array(); # We use sha1 by default. $this->assoc['hash'] = 'sha1'; $this->assoc['mac'] = $this->shared_secret('sha1'); $this->assoc['handle'] = $this->assoc_handle(); }
Creates a private association.
entailment
protected function dh() { if(empty($this->data['openid_dh_modulus'])) { $this->data['openid_dh_modulus'] = $this->default_modulus; } if(empty($this->data['openid_dh_gen'])) { $this->data['openid_dh_gen'] = $this->default_gen; } if(emp...
Encrypts the MAC key using DH key exchange.
entailment
protected function x_or($a, $b) { $length = strlen($a); for($i = 0; $i < $length; $i++) { $a[$i] = $a[$i] ^ $b[$i]; } return $a; }
XORs two strings. @param String $a @param String $b @return String $a ^ $b
entailment
protected function response($params) { $params += array('openid.ns' => $this->ns); return $this->data['openid_return_to'] . (strpos($this->data['openid_return_to'],'?') ? '&' : '?') . http_build_query($params, '', '&'); }
Prepares an indirect response url. @param array $params Parameters to be sent.
entailment
protected function errorResponse() { if(!empty($this->data['openid_return_to'])) { $response = array( 'openid.mode' => 'error', 'openid.error' => 'Invalid request' ); $this->redirect($this->response($response)); } else { header...
Outputs a direct error.
entailment
protected function positiveResponse($identity, $attributes) { # We generate a private association if there is none established. if(!$this->assoc) { $this->generateAssociation(); $this->assoc['private'] = true; } # We set openid.identity (and openid.cl...
Sends an positive assertion. @param String $identity the OP-Local Identifier that is being authenticated. @param Array $attributes User attributes to be sent.
entailment
protected function responseAttributes($attributes) { if(!$attributes) return array(); $ns = 'http://axschema.org/'; $response = array(); if(isset($this->data['ax'])) { $response['ns.ax'] = 'http://openid.net/srv/ax/1.0'; foreach($attributes as $name ...
Prepares an array of attributes to send
entailment
protected function b64dec($str) { $bytes = unpack('C*', base64_decode($str)); $n = 0; foreach($bytes as $byte) { $n = $this->add($this->mul($n, 256), $byte); } return $n; }
Converts base64 encoded number to it's decimal representation. @param String $str base64 encoded number. @return String Decimal representation of that number.
entailment
protected function decb64($num) { $bytes = array(); while($num) { array_unshift($bytes, $this->mod($num, 256)); $num = $this->div($num, 256); } if($bytes && $bytes[0] > 127) { array_unshift($bytes,0); } array_unshi...
Complements b64dec.
entailment
public function setParameter($key, $value) { if (!$this->parameters) { $this->parameters = array(); } $this->parameters[$key] = $value; return $this; }
Sets the parameter $key to value $value @param string $key @param string $value @return File
entailment
public function setGarbage($garbage, \DateTime $garbageTimestamp = null) { $this->garbage = $garbage; if ($garbageTimestamp == null) { $garbageTimestamp = new \DateTime(); } $this->setGarbageTimestamp($garbageTimestamp); return $this; }
@param boolean $garbage @param \DateTime $garbageTimestamp @return File
entailment
public function resolvePaymentState(OrderInterface $order) { $payment = $order->getPayment(); if($payment->getState() === PaymentInterface::STATE_COMPLETED) { $order->setPaymentState('completed'); } return; }
{@inheritdoc}
entailment
public function preFlush(PreFlushEventArgs $event) { $em = $event->getEntityManager(); $uow = $em->getUnitOfWork(); /* * We need to use the IdentityMap, because the update and persist collection stores entities, that have * computed changes, but translation data might have...
Before flushing the data, we have to check if some translation data was stored for an object. @param PreFlushEventArgs $event
entailment
public function preRemove(LifecycleEventArgs $args) { $entity = $args->getEntity(); $this->translator->deleteTranslationData($entity); }
If entity will be deleted, we need to delete all its translation data as well @param LifecycleEventArgs $args
entailment
public function postLoad(LifecycleEventArgs $args) { $entity = $args->getEntity(); $this->translator->translate($entity, $this->localeResolver->getLocale()); }
Load TranslationData into to entity if it's fetched from the database @param LifecycleEventArgs $args
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('enhavo_shop'); $rootNode ->children() ->scalarNode('driver')->defaultValue('doctrine/orm')->end() ->end() ->children() ...
{@inheritdoc}
entailment
public function editMessageText(int $message_id, string $text, string $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = true) { $this->parameters = [ 'chat_id' => $this->chat_id, 'message_id' => $message_id, 'text' => $text, 'repl...
\brief Edit text of a message sent by the bot. \details Use this method to edit text and game messages sent by the bot. [API reference](https://core.telegram.org/bots/api#editmessagetext) @param int $message_id Unique identifier of the sent message. @param string $text New text of the message. @param string $reply_mark...
entailment
public function editInlineMessageText(string $inline_message_id, string $text, string $reply_markup = null, string $parse_mode = 'HTML', bool $disable_web_preview = false) : bool { $parameters = [ 'inline_message_id' => $inline_message_id, 'text' => $text, 'reply_markup'...
\brief Edit text of a message sent via the bot. \details Use this method to edit text messages sent via the bot (for inline queries). [API reference](https://core.telegram.org/bots/api#editmessagetext) @param string $inline_message_id Identifier of the inline message. @param string $text New text of the message. @para...
entailment
public function editMessageReplyMarkup(int $message_id, string $inline_keyboard) { $this->parameters = [ 'chat_id' => $this->chat_id, 'message_id' => $message_id, 'reply_markup' => $inline_keyboard, ]; return $this->processRequest('editMessageReplyMarkup...
\brief Edit only the inline keyboard of a message. \details[API reference](https://core.telegram.org/bots/api#editmessagereplymarkup) @param int $message_id Identifier of the message to edit @param string $inline_keyboard Inlike keyboard array. [API reference](https://core.telegram.org/bots/api#inlinekeyboardmarkup) @r...
entailment
public function duplicate(\Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration $requestConfiguration, FactoryInterface $factory, ResourceInterface $originalResource) { if (null === $method = $requestConfiguration->getFactoryMethod()) { $method = 'duplicate'; } if (!meth...
{@inheritdoc}
entailment
public function load(ObjectManager $manager) { $this->manager = $manager; $this->loadData($this->getName()); }
{@inheritDoc}
entailment
public function loadData($name) { $file = sprintf('%s/../Resources/fixtures/%s.yml', __DIR__ , $name); if(!file_exists($file)) { throw new \Exception(sprintf('fixtures file "%s" not found for name "%s"', $file, $name)); } $data = Yaml::parse($file); $items = []; ...
Load the data from fixture file and insert it into the database @param $name @throws \Exception
entailment
protected function createImage($path) { $path = sprintf('%s/../Resources/images/%s', __DIR__, $path); $file = $this->container->get('enhavo_media.factory.file')->createFromPath($path); return $this->container->get('enhavo_media.media.media_manager')->saveFile($file); }
Save file and return its model. @param $path @return \Enhavo\Bundle\MediaBundle\Model\FileInterface @throws \Exception
entailment
public function createDateTime($value) { $date = null; if(is_string($value)) { $date = new \DateTime($value); } if(is_int($value)) { $date = new \DateTime(); $date->setTimestamp($value); } return $date; }
Return DateTime object @param $value @return \DateTime
entailment
public static function compressIp($ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return current(unpack('A4', inet_pton($ip))); } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { return current(unpack('A16', inet_pton($ip))); ...
Converts a printable IP into an unpacked binary string @author Mike Mackintosh - mike@bakeryphp.com @link http://www.highonphp.com/5-tips-for-working-with-ipv6-in-php @param string $ip @return string $bin
entailment
public static function expandIp($str) { if (strlen($str) == 16 OR strlen($str) == 4) { return inet_ntop(pack("A".strlen($str), $str)); } return false; }
Converts an unpacked binary string into a printable IP @author Mike Mackintosh - mike@bakeryphp.com @link http://www.highonphp.com/5-tips-for-working-with-ipv6-in-php @param string $str @return string $ip
entailment
public function run(int $type = WEBHOOK) { if ($type == WEBHOOK) { $this->_is_webhook = true; $this->init(); $this->processWebhookUpdate(); return; } if ($type == DEBUG) { $this->debug = true; } $this->init(); ...
\brief Start the bot. @param int $type How should the bot run?
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('enhavo_user'); $rootNode // Driver used by the resource bundle ->addDefaultsIfNotSet() ->children() ->scalarNode('driver')->defaultV...
{@inheritDoc}
entailment
public function addSubscriber(\Enhavo\Bundle\NewsletterBundle\Entity\Subscriber $subscriber) { $this->subscriber[] = $subscriber; return $this; }
Add subscriber @param \Enhavo\Bundle\NewsletterBundle\Entity\Subscriber $subscriber @return Group
entailment
public function removeSubscriber(\Enhavo\Bundle\NewsletterBundle\Entity\Subscriber $subscriber) { $this->subscriber->removeElement($subscriber); }
Remove subscriber @param \Enhavo\Bundle\NewsletterBundle\Entity\Subscriber $subscriber
entailment
public function load(array $config, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $config); $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $this->registerResources('enhavo_setting', $config['driver'], $co...
{@inheritdoc}
entailment
public function setOpenGraphImage(\Enhavo\Bundle\MediaBundle\Entity\File $openGraphImage = null) { $this->openGraphImage = $openGraphImage; return $this; }
Set openGraphImage @param \Enhavo\Bundle\MediaBundle\Entity\File $openGraphImage @return Content
entailment
public function setShipment(ShipmentInterface $shipment = null) { $shipment->setOrder($this); $this->shipment = $shipment; return $this; }
Set shipment @param ShipmentInterface $shipment @return Order
entailment
public function getBotID() : int { // If it is not valid if (!isset($this->_bot_id) || $this->_bot_id == 0) { // get it again $this->_bot_id = ($this->getMe())['id']; } return $this->_bot_id ?? 0; }
\brief Get bot ID using `getMe` method. @return int Bot id, 0 on errors.
entailment
protected function processRequest(string $method, string $class = '', $file = false) { $url = "$method?" . http_build_query($this->parameters); // If there is a file to upload if ($file === false) { $response = $this->execRequest($url); } else { $response = $...
\@internal brief Process an API method by taking method and parameter. \details optionally create a object of $class class name with the response as constructor param. @param string $method Method to call. @param array $param Parameter for the method. @param string $class Class name of the object to create using respon...
entailment
public function withChatId($chat_id, $method, ...$param) { $last_chat = $this->chat_id; $this->chat_id = $chat_id; $value = $this->$method(...$param); $this->chat_id = $last_chat; return $value; }
\brief Call a single api method using another chat_id without changing the current one. @param string|int $chat_id API method target chat_id. @param string $method Bot API method name. @param mixed ...$param Parameters for the API method. @return mixed The return value of the API method.
entailment
public function useChatId($chat_id, \closure $closure) { $last_chat = $this->chat_id; $this->chat_id = $chat_id; $value = $closure(); $this->chat_id = $last_chat; return $value; }
\brief Call the closure with the selected `chat_id`. \detail At the end of the method, $chat_id will still contain the original value. @param string|int $chat_id Target chat while executing the closure. @param closure $closure Closure to execute with the selected `chat_id`. @return mixed The return value of the closure...
entailment
public function releaseLock($name) { if (isset($this->files[$name])) { flock($this->files[$name], LOCK_UN); // @todo Can LOCK_UN fail? unset($this->locks[$name]); fclose($this->files[$name]); unset($this->files[$name]); return true; } ...
Release lock @param string $name name of lock @return bool
entailment
protected function getProperty($resource, $property) { if($property == '_self') { return $resource; } $propertyPath = explode('.', $property); if(count($propertyPath) > 1) { $property = array_shift($propertyPath); $newResource = $this->getPropert...
Return the value the given property and object. @param $resource @param $property @return mixed @throws PropertyNotExistsException
entailment
public function addTranslationData($entity, $propertyPath, $data) { $metadata = $this->metadataCollection->getMetadata($entity); $property = $metadata->getProperty($propertyPath); $strategy = $this->strategyResolver->getStrategy($property->getStrategy()); $strategy->addTranslationDat...
Add translation data, but does not store it. @param $entity @param string $propertyPath Property of the entity, that should be added @param mixed $data @throws \Exception
entailment
public function normalizeToTranslationData($entity, $propertyPath, $formData) { $metadata = $this->metadataCollection->getMetadata($entity); $property = $metadata->getProperty($propertyPath); $strategy = $this->strategyResolver->getStrategy($property->getStrategy()); return $strategy...
Normalize the form data. The data that a form contains after submit is a mix of the model data and the translation data. This function will return only the translation data. @param $entity @param $propertyPath @param $formData @return mixed @throws \Exception
entailment
public function deleteTranslationData($entity) { $metadata = $this->metadataCollection->getMetadata($entity); if($metadata === null) { return null; } $strategies = $this->strategyResolver->getStrategies(); foreach($strategies as $strategy) { $strategy...
Prepare deleting all translation data. Because this function should be called inside a doctrine hook, it contains no flush. @param $entity @return null @throws \Exception
entailment
public function getTranslationData($entity, Property $property) { $metadata = $this->metadataCollection->getMetadata($entity); if($metadata === null) { return null; } $metaProperty = $metadata->getProperty($property->getName()); if($metaProperty === null) { ...
Return the translation data, that is already stored in the database @param $entity @param Property $property @return null @throws \Exception
entailment
public function postFlush() { $strategies = $this->strategyResolver->getStrategies(); foreach($strategies as $strategy) { $strategy->postFlush(); } }
This function should be called after the flush was executed.
entailment
public function translate($entity, $locale) { $metadata = $this->metadataCollection->getMetadata($entity); if($metadata === null) { return null; } //translation data is stored inside the object if($locale === $this->defaultLocale) { return; } ...
Translate an entity. All stored translation data will be applied to this object. It should be called only inside the doctrine postLoad hook, because it doesn't handle recursive connections. @param $entity @param $locale @return null @throws \Exception
entailment
public function getTranslation($entity, $property, $locale) { $metadata = $this->metadataCollection->getMetadata($entity); if($metadata === null) { return null; } $property = $metadata->getProperty($property); if($property === null) { return null; ...
Translate a single property of an entity. @param $entity @param $property @param $locale @return null @throws \Exception
entailment
public function setFile(\Enhavo\Bundle\MediaBundle\Model\FileInterface $file = null) { $this->file = $file; return $this; }
Set file @param \Enhavo\Bundle\MediaBundle\Entity\File $file @return Setting
entailment
public function addFile(\Enhavo\Bundle\MediaBundle\Entity\File $file) { $this->files[] = $file; return $this; }
Add file @param \Enhavo\Bundle\MediaBundle\Entity\File $file @return Setting
entailment
public function removeFile(\Enhavo\Bundle\MediaBundle\Entity\File $file) { $this->files->removeElement($file); }
Remove file @param \Enhavo\Bundle\MediaBundle\Entity\File $file
entailment
public function init() { if (!isset($this->dom->documentElement)) { return false; } // Assume successful outcome $this->success = true; $bodyElems = $this->dom->getElementsByTagName('body'); // WTF multiple body nodes? if (null === $this->bodyCac...
Runs readability. Workflow: 1. Prep the document by removing script tags, css, etc. 2. Build readability's DOM tree. 3. Grab the article content from the current dom tree. 4. Replace the current DOM tree with the new one. 5. Read peacefully. @return bool true if we found content, false otherwise
entailment
public function postProcessContent(\DOMElement $articleContent) { if ($this->convertLinksToFootnotes && !preg_match('/\bwiki/', $this->url)) { $this->addFootnotes($articleContent); } }
Run any post-process modifications to article content as necessary. @param \DOMElement $articleContent
entailment
public function addFootnotes(\DOMElement $articleContent) { $footnotesWrapper = $this->dom->createElement('footer'); $footnotesWrapper->setAttribute('class', 'readability-footnotes'); $footnotesWrapper->setInnerHtml('<h3>References</h3>'); $articleFootnotes = $this->dom->createElemen...
For easier reading, convert this document to have footnotes at the bottom rather than inline links. @see http://www.roughtype.com/archives/2010/05/experiments_in.php @param \DOMElement $articleContent
entailment
public function prepArticle(\DOMNode $articleContent) { if (!$articleContent instanceof \DOMElement) { return; } $this->logger->debug($this->lightClean ? 'Light clean enabled.' : 'Standard clean enabled.'); $this->cleanStyles($articleContent); $this->killBreaks(...
Prepare the article node for display. Clean out any inline styles, iframes, forms, strip extraneous <p> tags, etc. @param \DOMNode $articleContent
entailment
public function getInnerText($e, $normalizeSpaces = true, $flattenLines = false) { if (null === $e || !isset($e->textContent) || '' === $e->textContent) { return ''; } $textContent = trim($e->textContent); if ($flattenLines) { $textContent = mb_ereg_replace(...
Get the inner text of a node. This also strips out any excess whitespace to be found. @param \DOMElement $e @param bool $normalizeSpaces (default: true) @param bool $flattenLines (default: false) @return string
entailment
public function cleanStyles($e) { if (!\is_object($e)) { return; } $elems = $e->getElementsByTagName('*'); foreach ($elems as $elem) { $elem->removeAttribute('style'); } }
Remove the style attribute on every $e and under. @param \DOMElement $e
entailment
public function getLinkDensity(\DOMElement $e, $excludeExternal = false) { $links = $e->getElementsByTagName('a'); $textLength = mb_strlen($this->getInnerText($e, true, true)); $linkLength = 0; for ($dRe = $this->domainRegExp, $i = 0, $il = $links->length; $i < $il; ++$i) { ...
Get the density of links as a percentage of the content This is the amount of text that is inside a link divided by the total text in the node. Can exclude external references to differentiate between simple text and menus/infoblocks. @param \DOMElement $e @param bool $excludeExternal @return int
entailment
public function getWeight(\DOMElement $e) { if (!$this->flagIsActive(self::FLAG_WEIGHT_ATTRIBUTES)) { return 0; } $weight = 0; // Look for a special classname $weight += $this->weightAttribute($e, 'class'); // Look for a special ID $weight += $thi...
Get an element relative weight. @param \DOMElement $e @return int
entailment
public function killBreaks(\DOMElement $node) { $html = $node->getInnerHTML(); $html = preg_replace($this->regexps['killBreaks'], '<br />', $html); $node->setInnerHtml($html); }
Remove extraneous break tags from a node. @param \DOMElement $node
entailment
public function clean(\DOMElement $e, $tag) { $currentItem = null; $targetList = $e->getElementsByTagName($tag); $isEmbed = ('audio' === $tag || 'video' === $tag || 'iframe' === $tag || 'object' === $tag || 'embed' === $tag); for ($y = $targetList->length - 1; $y >= 0; --$y) { ...
Clean a node of all elements of type "tag". (Unless it's a youtube/vimeo video. People love movies.). Updated 2012-09-18 to preserve youtube/vimeo iframes @param \DOMElement $e @param string $tag
entailment
public function cleanConditionally(\DOMElement $e, $tag) { if (!$this->flagIsActive(self::FLAG_CLEAN_CONDITIONALLY)) { return; } $tagsList = $e->getElementsByTagName($tag); $curTagsLength = $tagsList->length; $node = null; /* * Gather counts for...
Clean an element of all tags of type "tag" if they look fishy. "Fishy" is an algorithm based on content length, classnames, link density, number of images & embeds, etc. @param \DOMElement $e @param string $tag
entailment
public function cleanHeaders(\DOMElement $e) { for ($headerIndex = 1; $headerIndex < 3; ++$headerIndex) { $headers = $e->getElementsByTagName('h' . $headerIndex); for ($i = $headers->length - 1; $i >= 0; --$i) { if ($this->getWeight($headers->item($i)) < 0 || $this->...
Clean out spurious headers from an Element. Checks things like classnames and link density. @param \DOMElement $e
entailment
protected function getArticleTitle() { try { $curTitle = $origTitle = $this->getInnerText($this->dom->getElementsByTagName('title')->item(0)); } catch (\Exception $e) { $curTitle = ''; $origTitle = ''; } if (preg_match('/ [\|\-] /', $curTitle)) { ...
Get the article title as an H1. @return \DOMElement
entailment
protected function prepDocument() { /* * In some cases a body element can't be found (if the HTML is totally hosed for example) * so we create a new body node and append it to the document. */ if (null === $this->body) { $this->body = $this->dom->createElement(...
Prepare the HTML document for readability to scrape it. This includes things like stripping javascript, CSS, and handling terrible markup.
entailment
protected function initializeNode(\DOMElement $node) { if (!isset($node->tagName)) { return; } $readability = $this->dom->createAttribute('readability'); // this is our contentScore $readability->value = 0; $node->setAttributeNode($readability); ...
Initialize a node with the readability object. Also checks the className/id for special names to add to its score. @param \DOMElement $node
entailment
protected function grabArticle(\DOMElement $page = null) { if (!$page) { $page = $this->dom; } $xpath = null; $nodesToScore = []; if ($page instanceof \DOMDocument && isset($page->documentElement)) { $xpath = new \DOMXPath($page); } ...
Using a variety of metrics (content score, classname, element types), find the content that is most likely to be the stuff a user wants to read. Then return it wrapped up in a div. @param \DOMElement $page @return \DOMElement|false
entailment
protected function weightAttribute(\DOMElement $element, $attribute) { if (!$element->hasAttribute($attribute)) { return 0; } $weight = 0; // $attributeValue = trim($element->getAttribute('class')." ".$element->getAttribute('id')); $attributeValue = trim($element...
Get an element weight by attribute. Uses regular expressions to tell if this element looks good or bad. @param \DOMElement $element @param string $attribute @return int
entailment
protected function reinitBody() { if (!isset($this->body->childNodes)) { $this->body = $this->dom->createElement('body'); $this->body->setInnerHtml($this->bodyCache); } }
Will recreate previously deleted body property.
entailment
private function loadHtml() { $this->original_html = $this->html; $this->logger->debug('Parsing URL: ' . $this->url); if ($this->url) { $this->domainRegExp = '/' . strtr(preg_replace('/www\d*\./', '', parse_url($this->url, PHP_URL_HOST)), ['.' => '\.']) . '/'; } ...
Load HTML in a DOMDocument. Apply Pre filters Cleanup HTML using Tidy (or not). @todo This should be called in init() instead of from __construct
entailment
public function validate($value, Constraint $constraint) { if($value instanceof SubscriberInterface) { if($this->manager->exists($value, $value->getType())) { $this->context->buildViolation($constraint->message) ->setParameter('%email%', $value->getEmail()) ...
@param mixed $value @param Constraint $constraint
entailment
public function loadAllLanguages(string $dir = './localization') : bool { if ($handle = opendir($dir)) { // Iterate over all files while (false !== ($file = readdir($handle))) { // If the file is a JSON data file if (strlen($file) > 6 && substr($file, ...
\brief Load all localization files (like JSON) from a folder and set them in <code>$local</code> variable. \details Save all localization files, using JSON format, from a directory and put the contents in <code>$local</code> variable. Each file will be saved into <code>$local</code> with the first two letters of the f...
entailment
public function addFiles(FileInterface $file) { if ($this->files === null) { $this->files = new ArrayCollection(); } $this->files[] = $file; return $this; }
Add files @param FileInterface $file @return GalleryItem
entailment
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); if(isset($config['forms']) && is_array($config['forms'])) { foreach($config['forms'] as $name => $form) { ...
{@inheritdoc}
entailment
public function getStatus(int $default_status = -1) : int { $chat_id = $this->bot->chat_id; $redis = $this->bot->getRedis(); if ($redis->exists($chat_id . ':status')) { $this->status = $redis->get($chat_id . ':status'); return $this->status; } $redis-...
\brief Get current user status from Redis and set it in status variable. \details Throws an exception if the Redis connection is missing. @param int $default_status <i>Optional</i>. The default status to return if there is no status for the current user. @return int The status for the current user, $default_status if m...
entailment
public function setStatus(int $status) { $redis = $this->bot->getRedis(); $redis->set($this->bot->chat_id . ':status', $status); $this->status = $status; }
\brief Set the status of the bot in both Redis and $status. \details Throws an exception if the Redis connection is missing. @param int $status The new status of the bot.
entailment