repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
sebardo/ecommerce
EcommerceBundle/Service/CheckoutManager.php
CheckoutManager.getDelivery
public function getDelivery(Transaction $transaction = null) { if ($this->session->has('delivery-id')) { $delivery = $this->manager->getRepository('EcommerceBundle:Delivery')->find($this->session->get('delivery-id')); return $delivery; } $delivery = new Delivery(); /** @var Address $billingAddress */ $billingAddress = $this->manager->getRepository('EcommerceBundle:Address')->findOneBy(array( 'actor' => $this->securityContext->getToken()->getUser(), 'forBilling' => true )); if (false === is_null($billingAddress)) { $delivery->setFullName($this->securityContext->getToken()->getUser()->getFullName()); $delivery->setContactPerson($billingAddress->getContactPerson()); $delivery->setDni($billingAddress->getDni()); $delivery->setAddressInfo($billingAddress->getAddressInfo()); $delivery->setPhone($billingAddress->getPhone()); $delivery->setPhone2($billingAddress->getPhone2()); $delivery->setPreferredSchedule($billingAddress->getPreferredSchedule()); } $country = $this->manager->getRepository('CoreBundle:Country')->find('es'); $delivery->setCountry($country); if (false === is_null($transaction)) { $delivery->setTransaction($transaction); } return $delivery; }
php
public function getDelivery(Transaction $transaction = null) { if ($this->session->has('delivery-id')) { $delivery = $this->manager->getRepository('EcommerceBundle:Delivery')->find($this->session->get('delivery-id')); return $delivery; } $delivery = new Delivery(); /** @var Address $billingAddress */ $billingAddress = $this->manager->getRepository('EcommerceBundle:Address')->findOneBy(array( 'actor' => $this->securityContext->getToken()->getUser(), 'forBilling' => true )); if (false === is_null($billingAddress)) { $delivery->setFullName($this->securityContext->getToken()->getUser()->getFullName()); $delivery->setContactPerson($billingAddress->getContactPerson()); $delivery->setDni($billingAddress->getDni()); $delivery->setAddressInfo($billingAddress->getAddressInfo()); $delivery->setPhone($billingAddress->getPhone()); $delivery->setPhone2($billingAddress->getPhone2()); $delivery->setPreferredSchedule($billingAddress->getPreferredSchedule()); } $country = $this->manager->getRepository('CoreBundle:Country')->find('es'); $delivery->setCountry($country); if (false === is_null($transaction)) { $delivery->setTransaction($transaction); } return $delivery; }
[ "public", "function", "getDelivery", "(", "Transaction", "$", "transaction", "=", "null", ")", "{", "if", "(", "$", "this", "->", "session", "->", "has", "(", "'delivery-id'", ")", ")", "{", "$", "delivery", "=", "$", "this", "->", "manager", "->", "ge...
Build a delivery object for the current actor @param Transaction $transaction @return Delivery
[ "Build", "a", "delivery", "object", "for", "the", "current", "actor" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Service/CheckoutManager.php#L389-L423
train
sebardo/ecommerce
EcommerceBundle/Service/CheckoutManager.php
CheckoutManager.saveDelivery
public function saveDelivery(Delivery $delivery, array $params, $cart) { /** @var Carrier $carrier */ // $carrier = $this->manager->getRepository('ModelBundle:Carrier')->find($delivery->getCarrier()); if ('same' === $params['selectDelivery']) { $delivery->setDeliveryContactPerson($delivery->getContactPerson()); $delivery->setDeliveryDni($delivery->getDni()); $delivery->setDeliveryAddressInfo($delivery->getAddressInfo()); $delivery->setDeliveryPhone($delivery->getPhone()); $delivery->setDeliveryPhone2($delivery->getPhone2()); $delivery->setDeliveryPreferredSchedule($delivery->getPreferredSchedule()); } else if ('existing' === $params['selectDelivery']) { /** @var Address $address */ $address = $this->manager->getRepository('EcommerceBundle:Address')->find($params['existingDeliveryAddress']); $delivery->setDeliveryContactPerson($address->getContactPerson()); $delivery->setDeliveryDni($address->getDni()); $delivery->setDeliveryAddressInfo($address->getAddressInfo()); $delivery->setDeliveryPhone($address->getPhone()); $delivery->setDeliveryPhone2($address->getPhone2()); $delivery->setDeliveryPreferredSchedule($address->getPreferredSchedule()); } else if ('new' === $params['selectDelivery']) { $this->addUserDeliveryAddress($delivery); } $deliveryCountry = $this->manager->getRepository('CoreBundle:Country')->find('es'); $delivery->setDeliveryCountry($deliveryCountry); $total = 0; $productPurchases = $this->manager->getRepository('EcommerceBundle:ProductPurchase')->findByTransaction($delivery->getTransaction()); foreach ($productPurchases as $item) { if($item->getDeliveryExpenses()>0) $total = $total + $item->getDeliveryExpenses(); } $delivery->setExpenses($total); if($total>0) $delivery->setExpensesType('store_pickup'); else $delivery->setExpensesType('send'); $this->saveUserBillingAddress($delivery); $this->manager->persist($delivery); $this->manager->flush(); $this->session->set('delivery-id', $delivery->getId()); $this->session->set('select-delivery', $params['selectDelivery']); if ('existing' === $params['selectDelivery']) { $this->session->set('existing-delivery-address', intval($params['existingDeliveryAddress'])); } else { $this->session->remove('existing-delivery-address'); } $this->session->save(); }
php
public function saveDelivery(Delivery $delivery, array $params, $cart) { /** @var Carrier $carrier */ // $carrier = $this->manager->getRepository('ModelBundle:Carrier')->find($delivery->getCarrier()); if ('same' === $params['selectDelivery']) { $delivery->setDeliveryContactPerson($delivery->getContactPerson()); $delivery->setDeliveryDni($delivery->getDni()); $delivery->setDeliveryAddressInfo($delivery->getAddressInfo()); $delivery->setDeliveryPhone($delivery->getPhone()); $delivery->setDeliveryPhone2($delivery->getPhone2()); $delivery->setDeliveryPreferredSchedule($delivery->getPreferredSchedule()); } else if ('existing' === $params['selectDelivery']) { /** @var Address $address */ $address = $this->manager->getRepository('EcommerceBundle:Address')->find($params['existingDeliveryAddress']); $delivery->setDeliveryContactPerson($address->getContactPerson()); $delivery->setDeliveryDni($address->getDni()); $delivery->setDeliveryAddressInfo($address->getAddressInfo()); $delivery->setDeliveryPhone($address->getPhone()); $delivery->setDeliveryPhone2($address->getPhone2()); $delivery->setDeliveryPreferredSchedule($address->getPreferredSchedule()); } else if ('new' === $params['selectDelivery']) { $this->addUserDeliveryAddress($delivery); } $deliveryCountry = $this->manager->getRepository('CoreBundle:Country')->find('es'); $delivery->setDeliveryCountry($deliveryCountry); $total = 0; $productPurchases = $this->manager->getRepository('EcommerceBundle:ProductPurchase')->findByTransaction($delivery->getTransaction()); foreach ($productPurchases as $item) { if($item->getDeliveryExpenses()>0) $total = $total + $item->getDeliveryExpenses(); } $delivery->setExpenses($total); if($total>0) $delivery->setExpensesType('store_pickup'); else $delivery->setExpensesType('send'); $this->saveUserBillingAddress($delivery); $this->manager->persist($delivery); $this->manager->flush(); $this->session->set('delivery-id', $delivery->getId()); $this->session->set('select-delivery', $params['selectDelivery']); if ('existing' === $params['selectDelivery']) { $this->session->set('existing-delivery-address', intval($params['existingDeliveryAddress'])); } else { $this->session->remove('existing-delivery-address'); } $this->session->save(); }
[ "public", "function", "saveDelivery", "(", "Delivery", "$", "delivery", ",", "array", "$", "params", ",", "$", "cart", ")", "{", "/** @var Carrier $carrier */", "// $carrier = $this->manager->getRepository('ModelBundle:Carrier')->find($delivery->getCarrier());", "if", "(...
Save delivery fields from billing fields @param Delivery $delivery @param array $params
[ "Save", "delivery", "fields", "from", "billing", "fields" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Service/CheckoutManager.php#L431-L489
train
sebardo/ecommerce
EcommerceBundle/Service/CheckoutManager.php
CheckoutManager.saveUserBillingAddress
private function saveUserBillingAddress($delivery) { // get billing address /** @var Address $billingAddress */ $billingAddress = $this->manager->getRepository('EcommerceBundle:Address')->findOneBy(array( 'actor' => $this->securityContext->getToken()->getUser(), 'forBilling' => true )); // build new billing address when it does not exist if (is_null($billingAddress)) { $billingAddress = new Address(); $billingAddress->setForBilling(true); $billingAddress->setActor($this->securityContext->getToken()->getUser()); } $billingAddress->setContactPerson($delivery->getContactPerson()); $billingAddress->setDni($delivery->getDni()); $billingAddress->setAddressInfo($delivery->getAddressInfo()); $billingAddress->setPhone($delivery->getPhone()); $billingAddress->setPhone2($delivery->getPhone2()); $billingAddress->setPreferredSchedule($delivery->getPreferredSchedule()); $country = $this->manager->getRepository('CoreBundle:Country')->find('es'); $billingAddress->setCountry($country); $this->manager->persist($billingAddress); $this->manager->flush(); }
php
private function saveUserBillingAddress($delivery) { // get billing address /** @var Address $billingAddress */ $billingAddress = $this->manager->getRepository('EcommerceBundle:Address')->findOneBy(array( 'actor' => $this->securityContext->getToken()->getUser(), 'forBilling' => true )); // build new billing address when it does not exist if (is_null($billingAddress)) { $billingAddress = new Address(); $billingAddress->setForBilling(true); $billingAddress->setActor($this->securityContext->getToken()->getUser()); } $billingAddress->setContactPerson($delivery->getContactPerson()); $billingAddress->setDni($delivery->getDni()); $billingAddress->setAddressInfo($delivery->getAddressInfo()); $billingAddress->setPhone($delivery->getPhone()); $billingAddress->setPhone2($delivery->getPhone2()); $billingAddress->setPreferredSchedule($delivery->getPreferredSchedule()); $country = $this->manager->getRepository('CoreBundle:Country')->find('es'); $billingAddress->setCountry($country); $this->manager->persist($billingAddress); $this->manager->flush(); }
[ "private", "function", "saveUserBillingAddress", "(", "$", "delivery", ")", "{", "// get billing address", "/** @var Address $billingAddress */", "$", "billingAddress", "=", "$", "this", "->", "manager", "->", "getRepository", "(", "'EcommerceBundle:Address'", ")", "->", ...
Save user billing address @param Delivery $delivery
[ "Save", "user", "billing", "address" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Service/CheckoutManager.php#L496-L530
train
sebardo/ecommerce
EcommerceBundle/Service/CheckoutManager.php
CheckoutManager.cleanSession
public function cleanSession() { // remove checkout session parameters $this->session->remove('select-delivery'); $this->session->remove('delivery-id'); $this->session->remove('existing-delivery-address'); $this->session->remove('transaction-id'); // abandon cart $this->cartProvider->abandonCart(); }
php
public function cleanSession() { // remove checkout session parameters $this->session->remove('select-delivery'); $this->session->remove('delivery-id'); $this->session->remove('existing-delivery-address'); $this->session->remove('transaction-id'); // abandon cart $this->cartProvider->abandonCart(); }
[ "public", "function", "cleanSession", "(", ")", "{", "// remove checkout session parameters", "$", "this", "->", "session", "->", "remove", "(", "'select-delivery'", ")", ";", "$", "this", "->", "session", "->", "remove", "(", "'delivery-id'", ")", ";", "$", "...
Clean checkout parameters from session and void the shopping cart
[ "Clean", "checkout", "parameters", "from", "session", "and", "void", "the", "shopping", "cart" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Service/CheckoutManager.php#L630-L640
train
sebardo/ecommerce
EcommerceBundle/Service/CheckoutManager.php
CheckoutManager.getBillingAddress
public function getBillingAddress($actor=null) { if(is_null($actor)){ $actor = $this->securityContext->getToken()->getUser(); if (!$actor || !is_object($actor)) { throw new \LogicException( 'The getBillingAddress cannot be used without an authenticated user!' ); } } /** @var Address $address */ $address = $this->manager->getRepository('EcommerceBundle:Address') ->findOneBy(array( 'actor' => $actor, 'forBilling' => true )); // if it does not exist, create a new one if (is_null($address)) { $address = new Address(); $address->setForBilling(true); $country = $this->manager->getRepository('CoreBundle:Country')->find('es'); $address->setCountry($country); $address->setActor($actor); } return $address; }
php
public function getBillingAddress($actor=null) { if(is_null($actor)){ $actor = $this->securityContext->getToken()->getUser(); if (!$actor || !is_object($actor)) { throw new \LogicException( 'The getBillingAddress cannot be used without an authenticated user!' ); } } /** @var Address $address */ $address = $this->manager->getRepository('EcommerceBundle:Address') ->findOneBy(array( 'actor' => $actor, 'forBilling' => true )); // if it does not exist, create a new one if (is_null($address)) { $address = new Address(); $address->setForBilling(true); $country = $this->manager->getRepository('CoreBundle:Country')->find('es'); $address->setCountry($country); $address->setActor($actor); } return $address; }
[ "public", "function", "getBillingAddress", "(", "$", "actor", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "actor", ")", ")", "{", "$", "actor", "=", "$", "this", "->", "securityContext", "->", "getToken", "(", ")", "->", "getUser", "(", ")...
Get billing address @return Address
[ "Get", "billing", "address" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Service/CheckoutManager.php#L647-L674
train
sebardo/ecommerce
EcommerceBundle/Service/CheckoutManager.php
CheckoutManager.isCurrentUserOwner
public function isCurrentUserOwner(Transaction $transaction) { if($this->securityContext->getToken()->getUser()->isGranted('ROLE_ADMIN')){ return true; } $currentUserId = $this->securityContext->getToken()->getUser()->getId(); //actor owner if($transaction->getActor() instanceof Actor){ if($currentUserId == $transaction->getActor()->getId()){ return true; }elseif($currentUserId == $transaction->getItems()->first()->getProduct()->getActor()->getId()){ return true; } } return false; }
php
public function isCurrentUserOwner(Transaction $transaction) { if($this->securityContext->getToken()->getUser()->isGranted('ROLE_ADMIN')){ return true; } $currentUserId = $this->securityContext->getToken()->getUser()->getId(); //actor owner if($transaction->getActor() instanceof Actor){ if($currentUserId == $transaction->getActor()->getId()){ return true; }elseif($currentUserId == $transaction->getItems()->first()->getProduct()->getActor()->getId()){ return true; } } return false; }
[ "public", "function", "isCurrentUserOwner", "(", "Transaction", "$", "transaction", ")", "{", "if", "(", "$", "this", "->", "securityContext", "->", "getToken", "(", ")", "->", "getUser", "(", ")", "->", "isGranted", "(", "'ROLE_ADMIN'", ")", ")", "{", "re...
Check if current user is the transaction owner @param Transaction $transaction @return boolean
[ "Check", "if", "current", "user", "is", "the", "transaction", "owner" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Service/CheckoutManager.php#L683-L700
train
sebardo/ecommerce
EcommerceBundle/Service/CheckoutManager.php
CheckoutManager.processBankTransfer
public function processBankTransfer(Transaction $transaction) { $transaction->setStatus(Transaction::STATUS_PENDING_TRANSFER); $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('bank-transfer-test'); $transaction->setPaymentMethod($pm); $this->manager->persist($transaction); $this->manager->flush(); return true; }
php
public function processBankTransfer(Transaction $transaction) { $transaction->setStatus(Transaction::STATUS_PENDING_TRANSFER); $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('bank-transfer-test'); $transaction->setPaymentMethod($pm); $this->manager->persist($transaction); $this->manager->flush(); return true; }
[ "public", "function", "processBankTransfer", "(", "Transaction", "$", "transaction", ")", "{", "$", "transaction", "->", "setStatus", "(", "Transaction", "::", "STATUS_PENDING_TRANSFER", ")", ";", "$", "pm", "=", "$", "this", "->", "manager", "->", "getRepositor...
Process a bank transfer request @param Transaction $transaction
[ "Process", "a", "bank", "transfer", "request" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Service/CheckoutManager.php#L1549-L1559
train
sebardo/ecommerce
EcommerceBundle/Service/CheckoutManager.php
CheckoutManager.processRedsysTransaction
public function processRedsysTransaction($ds_response, Transaction $transaction) { if ($ds_response > 99) { return false; } $transaction->setStatus(Transaction::STATUS_PAID); $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('redsys'); $transaction->setPaymentMethod($pm); $this->manager->persist($transaction); $this->manager->flush(); return true; }
php
public function processRedsysTransaction($ds_response, Transaction $transaction) { if ($ds_response > 99) { return false; } $transaction->setStatus(Transaction::STATUS_PAID); $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('redsys'); $transaction->setPaymentMethod($pm); $this->manager->persist($transaction); $this->manager->flush(); return true; }
[ "public", "function", "processRedsysTransaction", "(", "$", "ds_response", ",", "Transaction", "$", "transaction", ")", "{", "if", "(", "$", "ds_response", ">", "99", ")", "{", "return", "false", ";", "}", "$", "transaction", "->", "setStatus", "(", "Transac...
Process a redsys transaction @param int $ds_response @param Transaction $transaction @return boolean
[ "Process", "a", "redsys", "transaction" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Service/CheckoutManager.php#L1569-L1583
train
themichaelhall/bluemvc-core
src/Collections/ResponseCookieCollection.php
ResponseCookieCollection.get
public function get(string $name): ?ResponseCookieInterface { if (!isset($this->responseCookies[$name])) { return null; } return $this->responseCookies[$name]; }
php
public function get(string $name): ?ResponseCookieInterface { if (!isset($this->responseCookies[$name])) { return null; } return $this->responseCookies[$name]; }
[ "public", "function", "get", "(", "string", "$", "name", ")", ":", "?", "ResponseCookieInterface", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "responseCookies", "[", "$", "name", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$...
Returns the response cookie by name if it exists, null otherwise. @since 1.0.0 @param string $name The name. @return ResponseCookieInterface|null The response cookie by name if it exists, null otherwise.
[ "Returns", "the", "response", "cookie", "by", "name", "if", "it", "exists", "null", "otherwise", "." ]
cbc8ccf8ed4f15ec6105837b29c2bd3db3f93680
https://github.com/themichaelhall/bluemvc-core/blob/cbc8ccf8ed4f15ec6105837b29c2bd3db3f93680/src/Collections/ResponseCookieCollection.php#L64-L71
train
themichaelhall/bluemvc-core
src/Collections/ResponseCookieCollection.php
ResponseCookieCollection.set
public function set(string $name, ResponseCookieInterface $responseCookie): void { $this->responseCookies[$name] = $responseCookie; }
php
public function set(string $name, ResponseCookieInterface $responseCookie): void { $this->responseCookies[$name] = $responseCookie; }
[ "public", "function", "set", "(", "string", "$", "name", ",", "ResponseCookieInterface", "$", "responseCookie", ")", ":", "void", "{", "$", "this", "->", "responseCookies", "[", "$", "name", "]", "=", "$", "responseCookie", ";", "}" ]
Sets a response cookie by name. @since 1.0.0 @param string $name The name. @param ResponseCookieInterface $responseCookie The response cookie.
[ "Sets", "a", "response", "cookie", "by", "name", "." ]
cbc8ccf8ed4f15ec6105837b29c2bd3db3f93680
https://github.com/themichaelhall/bluemvc-core/blob/cbc8ccf8ed4f15ec6105837b29c2bd3db3f93680/src/Collections/ResponseCookieCollection.php#L113-L116
train
Becklyn/BecklynSymfonyBase
src/LocalAccess.php
LocalAccess.isLocalIp
private function isLocalIp () { $ip = $this->serverData["REMOTE_ADDR"]; if (!is_string($ip)) { return false; } if (in_array($ip, ['127.0.0.1', 'fe80::1', '::1'], true)) { return true; } // allowed (= local) IPs include // 10.0.0.0 – 10.255.255.255 // 172.16.0.0 – 172.31.255.255 // 192.168.0.0 – 192.168.255.255 return 1 === preg_match("/^(10\\.|192\\.168\\.|172\\.(1[6-9]|2[0-9]|3[0-1])\\.)/", $ip); }
php
private function isLocalIp () { $ip = $this->serverData["REMOTE_ADDR"]; if (!is_string($ip)) { return false; } if (in_array($ip, ['127.0.0.1', 'fe80::1', '::1'], true)) { return true; } // allowed (= local) IPs include // 10.0.0.0 – 10.255.255.255 // 172.16.0.0 – 172.31.255.255 // 192.168.0.0 – 192.168.255.255 return 1 === preg_match("/^(10\\.|192\\.168\\.|172\\.(1[6-9]|2[0-9]|3[0-1])\\.)/", $ip); }
[ "private", "function", "isLocalIp", "(", ")", "{", "$", "ip", "=", "$", "this", "->", "serverData", "[", "\"REMOTE_ADDR\"", "]", ";", "if", "(", "!", "is_string", "(", "$", "ip", ")", ")", "{", "return", "false", ";", "}", "if", "(", "in_array", "(...
Returns whether remote IP is a local one @return bool
[ "Returns", "whether", "remote", "IP", "is", "a", "local", "one" ]
f912694c3e3ed46af37fe7ecf08bc503c77a5b41
https://github.com/Becklyn/BecklynSymfonyBase/blob/f912694c3e3ed46af37fe7ecf08bc503c77a5b41/src/LocalAccess.php#L69-L88
train
franzip/serp-page-serializer
src/SerpPageSerializer.php
SerpPageSerializer.serialize
public function serialize($serializablePage, $format) { // check if supported serialization format if (!SerpPageSerializerHelper::validFormat($format, self::$supportedFormatSerialization)) throw new \Franzip\SerpPageSerializer\Exceptions\UnsupportedSerializationFormatException('Invalid SerpPageSerializer $format: supported serialization formats are JSON, XML and YAML.'); // typecheck the object to serialize if (!SerpPageSerializerHelper::serializablePage($serializablePage)) throw new \Franzip\SerpPageSerializer\Exceptions\NonSerializableObjectException('Invalid SerpPageSerializer $serializablePage: you must supply a SerializableSerpPage object to serialize.'); $format = strtolower($format); $entries = $this->createEntries($serializablePage, $format); $serializablePage = $this->prepareForSerialization($serializablePage, $format, $entries); $serializedPage = $this->getSerializer()->serialize($serializablePage, $format); // beautify output if JSON $content = ($format == 'json') ? SerpPageSerializerHelper::prettyJSON($serializedPage) : $serializedPage; return new SerializedSerpPage($content); }
php
public function serialize($serializablePage, $format) { // check if supported serialization format if (!SerpPageSerializerHelper::validFormat($format, self::$supportedFormatSerialization)) throw new \Franzip\SerpPageSerializer\Exceptions\UnsupportedSerializationFormatException('Invalid SerpPageSerializer $format: supported serialization formats are JSON, XML and YAML.'); // typecheck the object to serialize if (!SerpPageSerializerHelper::serializablePage($serializablePage)) throw new \Franzip\SerpPageSerializer\Exceptions\NonSerializableObjectException('Invalid SerpPageSerializer $serializablePage: you must supply a SerializableSerpPage object to serialize.'); $format = strtolower($format); $entries = $this->createEntries($serializablePage, $format); $serializablePage = $this->prepareForSerialization($serializablePage, $format, $entries); $serializedPage = $this->getSerializer()->serialize($serializablePage, $format); // beautify output if JSON $content = ($format == 'json') ? SerpPageSerializerHelper::prettyJSON($serializedPage) : $serializedPage; return new SerializedSerpPage($content); }
[ "public", "function", "serialize", "(", "$", "serializablePage", ",", "$", "format", ")", "{", "// check if supported serialization format", "if", "(", "!", "SerpPageSerializerHelper", "::", "validFormat", "(", "$", "format", ",", "self", "::", "$", "supportedFormat...
Serialize a SerializableSerpPage object in the target format @param SerializableSerpPage $serializablePage @param string $format @return string
[ "Serialize", "a", "SerializableSerpPage", "object", "in", "the", "target", "format" ]
d3b67682e9a5ef87dcd56fb4191a23c4eeebc716
https://github.com/franzip/serp-page-serializer/blob/d3b67682e9a5ef87dcd56fb4191a23c4eeebc716/src/SerpPageSerializer.php#L58-L74
train
franzip/serp-page-serializer
src/SerpPageSerializer.php
SerpPageSerializer.deserialize
public function deserialize($serializedPage, $format) { // check if supported deserialization format if (!SerpPageSerializerHelper::validFormat($format, self::$supportedFormatDeserialization)) throw new \Franzip\SerpPageSerializer\Exceptions\UnsupportedDeserializationFormatException('Invalid SerpPageSerializer $format: supported deserialization formats are JSON and XML.'); // TODO: typecheck object if (!SerpPageSerializerHelper::deserializablePage($serializedPage)) throw new \Franzip\SerpPageSerializer\Exceptions\RuntimeException('Invalid SerpPageSerializer $serializedPage: you must supply a SerializedSerpPage object to deserialize.'); $format = strtolower($format); $targetClass = self::SERIALIZABLE_OBJECT_PREFIX . strtoupper($format); return $this->getSerializer()->deserialize($serializedPage->getContent(), $targetClass, $format); }
php
public function deserialize($serializedPage, $format) { // check if supported deserialization format if (!SerpPageSerializerHelper::validFormat($format, self::$supportedFormatDeserialization)) throw new \Franzip\SerpPageSerializer\Exceptions\UnsupportedDeserializationFormatException('Invalid SerpPageSerializer $format: supported deserialization formats are JSON and XML.'); // TODO: typecheck object if (!SerpPageSerializerHelper::deserializablePage($serializedPage)) throw new \Franzip\SerpPageSerializer\Exceptions\RuntimeException('Invalid SerpPageSerializer $serializedPage: you must supply a SerializedSerpPage object to deserialize.'); $format = strtolower($format); $targetClass = self::SERIALIZABLE_OBJECT_PREFIX . strtoupper($format); return $this->getSerializer()->deserialize($serializedPage->getContent(), $targetClass, $format); }
[ "public", "function", "deserialize", "(", "$", "serializedPage", ",", "$", "format", ")", "{", "// check if supported deserialization format", "if", "(", "!", "SerpPageSerializerHelper", "::", "validFormat", "(", "$", "format", ",", "self", "::", "$", "supportedForm...
Deserialize a serialized page. YAML deserialization is not currently supported. @param SerializedSerpPage $serializedPage @param string $format @return SerializableSerpPage
[ "Deserialize", "a", "serialized", "page", ".", "YAML", "deserialization", "is", "not", "currently", "supported", "." ]
d3b67682e9a5ef87dcd56fb4191a23c4eeebc716
https://github.com/franzip/serp-page-serializer/blob/d3b67682e9a5ef87dcd56fb4191a23c4eeebc716/src/SerpPageSerializer.php#L83-L95
train
franzip/serp-page-serializer
src/SerpPageSerializer.php
SerpPageSerializer.prepareForSerialization
private function prepareForSerialization($serializablePage, $format, $entries) { $engine = $serializablePage->getEngine(); $keyword = $serializablePage->getKeyword(); $pageUrl = $serializablePage->getPageUrl(); $pageNumber = $serializablePage->getPageNumber(); $age = $serializablePage->getAge(); return self::getFormatClassName($format, array($engine, $pageNumber, $pageUrl, $keyword, $age, $entries)); }
php
private function prepareForSerialization($serializablePage, $format, $entries) { $engine = $serializablePage->getEngine(); $keyword = $serializablePage->getKeyword(); $pageUrl = $serializablePage->getPageUrl(); $pageNumber = $serializablePage->getPageNumber(); $age = $serializablePage->getAge(); return self::getFormatClassName($format, array($engine, $pageNumber, $pageUrl, $keyword, $age, $entries)); }
[ "private", "function", "prepareForSerialization", "(", "$", "serializablePage", ",", "$", "format", ",", "$", "entries", ")", "{", "$", "engine", "=", "$", "serializablePage", "->", "getEngine", "(", ")", ";", "$", "keyword", "=", "$", "serializablePage", "-...
Map SerializableSerpPage to an easy serializable SerpPage. The serialization format is resolved at runtime. @param SerializableSerpPage $serializablePage @param string $format @param array $entries @return SerpPageJSON|SerpPageXML|SerpPageYML
[ "Map", "SerializableSerpPage", "to", "an", "easy", "serializable", "SerpPage", ".", "The", "serialization", "format", "is", "resolved", "at", "runtime", "." ]
d3b67682e9a5ef87dcd56fb4191a23c4eeebc716
https://github.com/franzip/serp-page-serializer/blob/d3b67682e9a5ef87dcd56fb4191a23c4eeebc716/src/SerpPageSerializer.php#L114-L123
train
franzip/serp-page-serializer
src/SerpPageSerializer.php
SerpPageSerializer.createEntries
private function createEntries($serializablePage, $format) { $result = array(); $entries = $serializablePage->getEntries(); for ($i = 0; $i < count($entries); $i++) { $args = array(($i + 1), $entries[$i]['url'], $entries[$i]['title'], $entries[$i]['snippet']); array_push($result, self::getFormatClassName($format, $args, true)); } return $result; }
php
private function createEntries($serializablePage, $format) { $result = array(); $entries = $serializablePage->getEntries(); for ($i = 0; $i < count($entries); $i++) { $args = array(($i + 1), $entries[$i]['url'], $entries[$i]['title'], $entries[$i]['snippet']); array_push($result, self::getFormatClassName($format, $args, true)); } return $result; }
[ "private", "function", "createEntries", "(", "$", "serializablePage", ",", "$", "format", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "entries", "=", "$", "serializablePage", "->", "getEntries", "(", ")", ";", "for", "(", "$", "i", "=", ...
Map SerializableSerpPage entries to SerpPageEntries. The serialization format is resolved at runtime. @param SerializableSerpPage $serializablePage @param string $format @return SerpPageEntryJSON|SerpPageEntryXML|SerpPageEntryYAML
[ "Map", "SerializableSerpPage", "entries", "to", "SerpPageEntries", ".", "The", "serialization", "format", "is", "resolved", "at", "runtime", "." ]
d3b67682e9a5ef87dcd56fb4191a23c4eeebc716
https://github.com/franzip/serp-page-serializer/blob/d3b67682e9a5ef87dcd56fb4191a23c4eeebc716/src/SerpPageSerializer.php#L132-L141
train
demisang/longlog-php-sdk
src/LongLog.php
LongLog.setJobName
public function setJobName($name) { if (!is_string($name)) { throw new InvalidArgumentException('Job name must be a string'); } $name = trim($name); $strlen = mb_strlen($name); if (!$strlen) { throw new InvalidArgumentException('Job name cannot be empty'); } elseif ($strlen < 2 || $strlen > 255) { throw new InvalidArgumentException('Job name length must be in range 2-255 characters'); } $this->jobName = $name; return $this; }
php
public function setJobName($name) { if (!is_string($name)) { throw new InvalidArgumentException('Job name must be a string'); } $name = trim($name); $strlen = mb_strlen($name); if (!$strlen) { throw new InvalidArgumentException('Job name cannot be empty'); } elseif ($strlen < 2 || $strlen > 255) { throw new InvalidArgumentException('Job name length must be in range 2-255 characters'); } $this->jobName = $name; return $this; }
[ "public", "function", "setJobName", "(", "$", "name", ")", "{", "if", "(", "!", "is_string", "(", "$", "name", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Job name must be a string'", ")", ";", "}", "$", "name", "=", "trim", "(", "$...
Set job name @param string $name @return $this
[ "Set", "job", "name" ]
f6b2944acaf195954b52bf5b89b09c8096fd597f
https://github.com/demisang/longlog-php-sdk/blob/f6b2944acaf195954b52bf5b89b09c8096fd597f/src/LongLog.php#L90-L108
train
demisang/longlog-php-sdk
src/LongLog.php
LongLog.setPayload
public function setPayload($data) { if (!is_string($data)) { if (is_array($data)) { $data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } else { $data = serialize($data); } } $maxLength = 255; if (mb_strlen($data) > $maxLength) { // Truncate too long payload $data = mb_substr($data, 0, $maxLength - 3) . '...'; } $this->payload = $data ? $data : null; return $this; }
php
public function setPayload($data) { if (!is_string($data)) { if (is_array($data)) { $data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } else { $data = serialize($data); } } $maxLength = 255; if (mb_strlen($data) > $maxLength) { // Truncate too long payload $data = mb_substr($data, 0, $maxLength - 3) . '...'; } $this->payload = $data ? $data : null; return $this; }
[ "public", "function", "setPayload", "(", "$", "data", ")", "{", "if", "(", "!", "is_string", "(", "$", "data", ")", ")", "{", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "$", "data", "=", "json_encode", "(", "$", "data", ",", "JSON_UN...
Set payload value @param mixed $data [1, 4, 5] or "1,4,5" or Object @return $this
[ "Set", "payload", "value" ]
f6b2944acaf195954b52bf5b89b09c8096fd597f
https://github.com/demisang/longlog-php-sdk/blob/f6b2944acaf195954b52bf5b89b09c8096fd597f/src/LongLog.php#L127-L146
train
demisang/longlog-php-sdk
src/LongLog.php
LongLog.setDuration
public function setDuration($seconds) { $seconds = round($seconds, 3); if ($seconds < 0 || $seconds > 999999.999) { throw new InvalidArgumentException('Duration seconds must be in range 0-999999.999'); } $this->duration = $seconds; return $this; }
php
public function setDuration($seconds) { $seconds = round($seconds, 3); if ($seconds < 0 || $seconds > 999999.999) { throw new InvalidArgumentException('Duration seconds must be in range 0-999999.999'); } $this->duration = $seconds; return $this; }
[ "public", "function", "setDuration", "(", "$", "seconds", ")", "{", "$", "seconds", "=", "round", "(", "$", "seconds", ",", "3", ")", ";", "if", "(", "$", "seconds", "<", "0", "||", "$", "seconds", ">", "999999.999", ")", "{", "throw", "new", "Inva...
Set custom duration value @param float $seconds min 0; max 999999.999 @return $this
[ "Set", "custom", "duration", "value" ]
f6b2944acaf195954b52bf5b89b09c8096fd597f
https://github.com/demisang/longlog-php-sdk/blob/f6b2944acaf195954b52bf5b89b09c8096fd597f/src/LongLog.php#L175-L186
train
novuso/common
src/Domain/Type/FloatObject.php
FloatObject.round
public function round(int $precision = 0, ?RoundingMode $roundingMode = null): FloatObject { if ($roundingMode === null) { $roundingMode = RoundingMode::HALF_UP(); } return new static((float) round($this->value, $precision, $roundingMode->value())); }
php
public function round(int $precision = 0, ?RoundingMode $roundingMode = null): FloatObject { if ($roundingMode === null) { $roundingMode = RoundingMode::HALF_UP(); } return new static((float) round($this->value, $precision, $roundingMode->value())); }
[ "public", "function", "round", "(", "int", "$", "precision", "=", "0", ",", "?", "RoundingMode", "$", "roundingMode", "=", "null", ")", ":", "FloatObject", "{", "if", "(", "$", "roundingMode", "===", "null", ")", "{", "$", "roundingMode", "=", "RoundingM...
Creates a float that represents the rounded value @param int $precision The number of digits to round to @param RoundingMode|null $roundingMode The rounding mode @return FloatObject
[ "Creates", "a", "float", "that", "represents", "the", "rounded", "value" ]
7d0e5a4f4c79c9622e068efc8b7c70815c460863
https://github.com/novuso/common/blob/7d0e5a4f4c79c9622e068efc8b7c70815c460863/src/Domain/Type/FloatObject.php#L138-L145
train
mmanos/laravel-metable
src/Mmanos/Metable/QueryBuilder.php
QueryBuilder.setModel
public function setModel($model) { $this->model = $model; $this->from($this->model->metableTable() . ' AS m'); if ($this->model->metableTableSoftDeletes()) { $this->whereNull('m.' . $this->model->getDeletedAtColumn()); } return $this; }
php
public function setModel($model) { $this->model = $model; $this->from($this->model->metableTable() . ' AS m'); if ($this->model->metableTableSoftDeletes()) { $this->whereNull('m.' . $this->model->getDeletedAtColumn()); } return $this; }
[ "public", "function", "setModel", "(", "$", "model", ")", "{", "$", "this", "->", "model", "=", "$", "model", ";", "$", "this", "->", "from", "(", "$", "this", "->", "model", "->", "metableTable", "(", ")", ".", "' AS m'", ")", ";", "if", "(", "$...
Set the model for this instance. @param \Illuminate\Database\Eloquent\Model $model @return QueryBuilder
[ "Set", "the", "model", "for", "this", "instance", "." ]
f6a6bdcebcf7eefd42e9d58c37e3206361f147de
https://github.com/mmanos/laravel-metable/blob/f6a6bdcebcf7eefd42e9d58c37e3206361f147de/src/Mmanos/Metable/QueryBuilder.php#L23-L34
train
mmanos/laravel-metable
src/Mmanos/Metable/QueryBuilder.php
QueryBuilder.whereAnyMetaId
public function whereAnyMetaId(array $metas) { $filters = array(); foreach ($metas as $meta => $data) { $value = is_array($data) ? Arr::get($data, 0) : $data; $operator = is_array($data) ? Arr::get($data, 1, '=') : '='; $filters[] = array('id' => $meta, 'value' => $value, 'operator' => $operator); } $this->filters[]['metas'] = $filters; return $this; }
php
public function whereAnyMetaId(array $metas) { $filters = array(); foreach ($metas as $meta => $data) { $value = is_array($data) ? Arr::get($data, 0) : $data; $operator = is_array($data) ? Arr::get($data, 1, '=') : '='; $filters[] = array('id' => $meta, 'value' => $value, 'operator' => $operator); } $this->filters[]['metas'] = $filters; return $this; }
[ "public", "function", "whereAnyMetaId", "(", "array", "$", "metas", ")", "{", "$", "filters", "=", "array", "(", ")", ";", "foreach", "(", "$", "metas", "as", "$", "meta", "=>", "$", "data", ")", "{", "$", "value", "=", "is_array", "(", "$", "data"...
Filter the query on any of the given meta ids and meta values. @param array $metas @return QueryBuilder
[ "Filter", "the", "query", "on", "any", "of", "the", "given", "meta", "ids", "and", "meta", "values", "." ]
f6a6bdcebcf7eefd42e9d58c37e3206361f147de
https://github.com/mmanos/laravel-metable/blob/f6a6bdcebcf7eefd42e9d58c37e3206361f147de/src/Mmanos/Metable/QueryBuilder.php#L244-L258
train
budkit/budkit-framework
src/Budkit/Datastore/Encrypt.php
Encrypt.encode
public function encode($string) { if (empty($string) || empty($this->key)) { throw new \Exception("Can not encrypt with an empty key or no data"); return false; } $publicKey = $this->generateKey($string); $privateKey = $this->key; //Get a SHA-1 hashKey $hashKey = sha1($privateKey . "+" . (string)$publicKey); $stringArray = str_split($string); $hashArray = str_split($hashKey); $cipherNoise = str_split($publicKey, 2); $counter = 0; for ($i = 0; $i < sizeof($stringArray); $i++) { if ($counter > 40) $counter = 0; $cryptChar = ord((string)$stringArray[$i]) + ord((string)$hashArray[$counter]); $cryptChar -= floor($cryptChar / 127) * 127; $cipherStream[$i] = dechex($cryptChar); $counter++; } //print_R($cipherNoise); $cipherNoiseSize = count($cipherNoise); $cipher = implode("|x", $cipherStream); $cipher .= "|x::|x" . ord((string)$cipherNoiseSize) . "|x"; $cipher .= implode("|x", $cipherNoise); //echo $cipher; return $cipher; }
php
public function encode($string) { if (empty($string) || empty($this->key)) { throw new \Exception("Can not encrypt with an empty key or no data"); return false; } $publicKey = $this->generateKey($string); $privateKey = $this->key; //Get a SHA-1 hashKey $hashKey = sha1($privateKey . "+" . (string)$publicKey); $stringArray = str_split($string); $hashArray = str_split($hashKey); $cipherNoise = str_split($publicKey, 2); $counter = 0; for ($i = 0; $i < sizeof($stringArray); $i++) { if ($counter > 40) $counter = 0; $cryptChar = ord((string)$stringArray[$i]) + ord((string)$hashArray[$counter]); $cryptChar -= floor($cryptChar / 127) * 127; $cipherStream[$i] = dechex($cryptChar); $counter++; } //print_R($cipherNoise); $cipherNoiseSize = count($cipherNoise); $cipher = implode("|x", $cipherStream); $cipher .= "|x::|x" . ord((string)$cipherNoiseSize) . "|x"; $cipher .= implode("|x", $cipherNoise); //echo $cipher; return $cipher; }
[ "public", "function", "encode", "(", "$", "string", ")", "{", "if", "(", "empty", "(", "$", "string", ")", "||", "empty", "(", "$", "this", "->", "key", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Can not encrypt with an empty key or no data\...
Encodes a given string @param string $string @return string encoded string
[ "Encodes", "a", "given", "string" ]
0635061815fe07a8c63f9514b845d199b3c0d485
https://github.com/budkit/budkit-framework/blob/0635061815fe07a8c63f9514b845d199b3c0d485/src/Budkit/Datastore/Encrypt.php#L114-L155
train
budkit/budkit-framework
src/Budkit/Datastore/Encrypt.php
Encrypt.generateKey
public static function generateKey($txt, $length = null) { date_default_timezone_set('UTC'); $possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ"; $maxlength = (empty($length) || (int)$length > strlen($possible)) ? strlen($possible) : (int)$length; $random = ""; $i = 0; while ($i < ($maxlength / 5)) { // pick a random character from the possible ones $char = substr($possible, mt_rand(0, $maxlength - 1), 1); if (!strstr($random, $char)) { $random .= $char; $i++; } } $salt = time() . $random; $rand = mt_rand(); $key = md5($rand . $txt . $salt); return $key; }
php
public static function generateKey($txt, $length = null) { date_default_timezone_set('UTC'); $possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ"; $maxlength = (empty($length) || (int)$length > strlen($possible)) ? strlen($possible) : (int)$length; $random = ""; $i = 0; while ($i < ($maxlength / 5)) { // pick a random character from the possible ones $char = substr($possible, mt_rand(0, $maxlength - 1), 1); if (!strstr($random, $char)) { $random .= $char; $i++; } } $salt = time() . $random; $rand = mt_rand(); $key = md5($rand . $txt . $salt); return $key; }
[ "public", "static", "function", "generateKey", "(", "$", "txt", ",", "$", "length", "=", "null", ")", "{", "date_default_timezone_set", "(", "'UTC'", ")", ";", "$", "possible", "=", "\"2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ\"", ";", "$", "maxlength", "=", ...
Generates a random encryption key @param string $txt @return string
[ "Generates", "a", "random", "encryption", "key" ]
0635061815fe07a8c63f9514b845d199b3c0d485
https://github.com/budkit/budkit-framework/blob/0635061815fe07a8c63f9514b845d199b3c0d485/src/Budkit/Datastore/Encrypt.php#L163-L189
train
budkit/budkit-framework
src/Budkit/Datastore/Encrypt.php
Encrypt.decode
public function decode($encrypted) { //$cipher_all = explode("/", $cipher_in); //$cipher = $cipher_all[0]; $blocks = explode("|x", $encrypted); $delimiter = array_search("::", $blocks); $cipherStream = array_slice($blocks, 0, (int)$delimiter); unset($blocks[(int)$delimiter]); unset($blocks[(int)$delimiter + 1]); $publicKeyArray = array_slice($blocks, (int)$delimiter); $publicKey = implode('', $publicKeyArray); $privateKey = $this->key; $hashKey = sha1($privateKey . "+" . (string)$publicKey); $hashArray = str_split($hashKey); $counter = 0; for ($i = 0; $i < sizeof($cipherStream); $i++) { if ($counter > 40) $counter = 0; $cryptChar = hexdec($cipherStream[$i]) - ord((string)$hashArray[$counter]); $cryptChar -= floor($cryptChar / 127) * 127; $cipherText[$i] = chr($cryptChar); $counter++; } $plaintext = implode("", $cipherText); return $plaintext; }
php
public function decode($encrypted) { //$cipher_all = explode("/", $cipher_in); //$cipher = $cipher_all[0]; $blocks = explode("|x", $encrypted); $delimiter = array_search("::", $blocks); $cipherStream = array_slice($blocks, 0, (int)$delimiter); unset($blocks[(int)$delimiter]); unset($blocks[(int)$delimiter + 1]); $publicKeyArray = array_slice($blocks, (int)$delimiter); $publicKey = implode('', $publicKeyArray); $privateKey = $this->key; $hashKey = sha1($privateKey . "+" . (string)$publicKey); $hashArray = str_split($hashKey); $counter = 0; for ($i = 0; $i < sizeof($cipherStream); $i++) { if ($counter > 40) $counter = 0; $cryptChar = hexdec($cipherStream[$i]) - ord((string)$hashArray[$counter]); $cryptChar -= floor($cryptChar / 127) * 127; $cipherText[$i] = chr($cryptChar); $counter++; } $plaintext = implode("", $cipherText); return $plaintext; }
[ "public", "function", "decode", "(", "$", "encrypted", ")", "{", "//$cipher_all = explode(\"/\", $cipher_in);", "//$cipher = $cipher_all[0];", "$", "blocks", "=", "explode", "(", "\"|x\"", ",", "$", "encrypted", ")", ";", "$", "delimiter", "=", "array_search", "(", ...
Decodes a previously encode string. @param string $encrypted @return string Decoded string
[ "Decodes", "a", "previously", "encode", "string", "." ]
0635061815fe07a8c63f9514b845d199b3c0d485
https://github.com/budkit/budkit-framework/blob/0635061815fe07a8c63f9514b845d199b3c0d485/src/Budkit/Datastore/Encrypt.php#L218-L255
train
weckx/wcx-syslog
library/Wcx/Syslog/Transport/Udp.php
Udp.send
public function send(MessageInterface $message, $target) { $msg = $message->getMessageString(); if (strpos($target, ':')) { list($host, $port) = explode(':', $target); } else { $host = $target; $port = self::DEFAULT_UDP_PORT; } $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if ($sock === false) { $errorCode = socket_last_error(); $errorMsg = socket_strerror($errorCode); throw new \RuntimeException("Error creating socket: [$errorCode] $errorMsg"); } socket_sendto($sock, $msg, strlen($msg), 0, $host, $port); socket_close($sock); }
php
public function send(MessageInterface $message, $target) { $msg = $message->getMessageString(); if (strpos($target, ':')) { list($host, $port) = explode(':', $target); } else { $host = $target; $port = self::DEFAULT_UDP_PORT; } $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if ($sock === false) { $errorCode = socket_last_error(); $errorMsg = socket_strerror($errorCode); throw new \RuntimeException("Error creating socket: [$errorCode] $errorMsg"); } socket_sendto($sock, $msg, strlen($msg), 0, $host, $port); socket_close($sock); }
[ "public", "function", "send", "(", "MessageInterface", "$", "message", ",", "$", "target", ")", "{", "$", "msg", "=", "$", "message", "->", "getMessageString", "(", ")", ";", "if", "(", "strpos", "(", "$", "target", ",", "':'", ")", ")", "{", "list",...
Send the syslog to target host using the UDP protocol. Note that the UDP protocol is stateless, which means we can't confirm that the message was received by the other end @param MessageInterface $message @param string $target Host:port, if port not specified uses default 514 @return void @throws \RuntimeException If there's an error creating the socket
[ "Send", "the", "syslog", "to", "target", "host", "using", "the", "UDP", "protocol", ".", "Note", "that", "the", "UDP", "protocol", "is", "stateless", "which", "means", "we", "can", "t", "confirm", "that", "the", "message", "was", "received", "by", "the", ...
2ec40409a7b5393751ebf9051a33d829e6fc313e
https://github.com/weckx/wcx-syslog/blob/2ec40409a7b5393751ebf9051a33d829e6fc313e/library/Wcx/Syslog/Transport/Udp.php#L34-L53
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.getMainJsFileName
private static function getMainJsFileName(string $realPath): string { $parts = pathinfo($realPath); return $parts['dirname'].'/'.$parts['filename'].'.main.'.$parts['extension']; }
php
private static function getMainJsFileName(string $realPath): string { $parts = pathinfo($realPath); return $parts['dirname'].'/'.$parts['filename'].'.main.'.$parts['extension']; }
[ "private", "static", "function", "getMainJsFileName", "(", "string", "$", "realPath", ")", ":", "string", "{", "$", "parts", "=", "pathinfo", "(", "$", "realPath", ")", ";", "return", "$", "parts", "[", "'dirname'", "]", ".", "'/'", ".", "$", "parts", ...
Returns the 'main' file of a page specific main JavaScript file. @param string $realPath @return string
[ "Returns", "the", "main", "file", "of", "a", "page", "specific", "main", "JavaScript", "file", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L70-L75
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.minimizeResource
protected function minimizeResource(string $resource, ?string $fullPathName): string { list($std_out, $std_err) = $this->runProcess($this->minifyCommand, $resource); if ($std_err) $this->logInfo($std_err); return $std_out; }
php
protected function minimizeResource(string $resource, ?string $fullPathName): string { list($std_out, $std_err) = $this->runProcess($this->minifyCommand, $resource); if ($std_err) $this->logInfo($std_err); return $std_out; }
[ "protected", "function", "minimizeResource", "(", "string", "$", "resource", ",", "?", "string", "$", "fullPathName", ")", ":", "string", "{", "list", "(", "$", "std_out", ",", "$", "std_err", ")", "=", "$", "this", "->", "runProcess", "(", "$", "this", ...
Minimizes JavaScript code. @param string $resource The JavaScript code. @param string|null $fullPathName The full pathname of the JavaScript file. @return string The minimized JavaScript code.
[ "Minimizes", "JavaScript", "code", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L130-L137
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.combine
private function combine(string $realPath): array { $config = $this->extractConfigFromMainFile(self::getMainJsFileName($realPath)); // Create temporary file with config. $tmp_name1 = tempnam('.', 'abc_'); $handle = fopen($tmp_name1, 'w'); fwrite($handle, $config); fclose($handle); // Create temporary file for combined JavaScript code. $tmp_name2 = tempnam($this->resourceDirFullPath, 'abc_'); // Run r.js. $command = [$this->combineCommand, '-o', $tmp_name1, 'baseUrl='.$this->resourceDirFullPath, 'optimize=none', 'name='.$this->getNamespaceFromResourceFilename($realPath), 'out='.$tmp_name2]; $output = $this->execCommand($command); // Get all files of the combined code. $parts = []; $trigger = array_search('----------------', $output); foreach ($output as $index => $file) { if ($index>$trigger && !empty($file)) { $parts[] = $file; } } // Get the combined the JavaScript code. $code = file_get_contents($tmp_name2); if ($code===false) $this->logError("Unable to read file '%s'.", $tmp_name2); // Get require.js $path = $this->parentResourceDirFullPath.'/'.$this->requireJsPath; $require_js = file_get_contents($path); if ($code===false) $this->logError("Unable to read file '%s'.", $path); // Combine require.js and all required includes. $code = $require_js.$code; // Remove temporary files. unlink($tmp_name2); unlink($tmp_name1); return ['code' => $code, 'parts' => $parts]; }
php
private function combine(string $realPath): array { $config = $this->extractConfigFromMainFile(self::getMainJsFileName($realPath)); // Create temporary file with config. $tmp_name1 = tempnam('.', 'abc_'); $handle = fopen($tmp_name1, 'w'); fwrite($handle, $config); fclose($handle); // Create temporary file for combined JavaScript code. $tmp_name2 = tempnam($this->resourceDirFullPath, 'abc_'); // Run r.js. $command = [$this->combineCommand, '-o', $tmp_name1, 'baseUrl='.$this->resourceDirFullPath, 'optimize=none', 'name='.$this->getNamespaceFromResourceFilename($realPath), 'out='.$tmp_name2]; $output = $this->execCommand($command); // Get all files of the combined code. $parts = []; $trigger = array_search('----------------', $output); foreach ($output as $index => $file) { if ($index>$trigger && !empty($file)) { $parts[] = $file; } } // Get the combined the JavaScript code. $code = file_get_contents($tmp_name2); if ($code===false) $this->logError("Unable to read file '%s'.", $tmp_name2); // Get require.js $path = $this->parentResourceDirFullPath.'/'.$this->requireJsPath; $require_js = file_get_contents($path); if ($code===false) $this->logError("Unable to read file '%s'.", $path); // Combine require.js and all required includes. $code = $require_js.$code; // Remove temporary files. unlink($tmp_name2); unlink($tmp_name1); return ['code' => $code, 'parts' => $parts]; }
[ "private", "function", "combine", "(", "string", "$", "realPath", ")", ":", "array", "{", "$", "config", "=", "$", "this", "->", "extractConfigFromMainFile", "(", "self", "::", "getMainJsFileName", "(", "$", "realPath", ")", ")", ";", "// Create temporary file...
Combines all JavaScript files required by a main JavaScript file. @param string $realPath The path to the main JavaScript file. @return array The combined code and parts.
[ "Combines", "all", "JavaScript", "files", "required", "by", "a", "main", "JavaScript", "file", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L257-L308
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.execCommand
private function execCommand(array $command): array { $this->logVerbose('Execute: %s', implode(' ', $command)); list($output, $ret) = ProgramExecution::exec1($command, null); if ($ret!=0) { foreach ($output as $line) { $this->logInfo($line); } $this->logError("Error executing '%s'.", implode(' ', $command)); } else { foreach ($output as $line) { $this->logVerbose($line); } } return $output; }
php
private function execCommand(array $command): array { $this->logVerbose('Execute: %s', implode(' ', $command)); list($output, $ret) = ProgramExecution::exec1($command, null); if ($ret!=0) { foreach ($output as $line) { $this->logInfo($line); } $this->logError("Error executing '%s'.", implode(' ', $command)); } else { foreach ($output as $line) { $this->logVerbose($line); } } return $output; }
[ "private", "function", "execCommand", "(", "array", "$", "command", ")", ":", "array", "{", "$", "this", "->", "logVerbose", "(", "'Execute: %s'", ",", "implode", "(", "' '", ",", "$", "command", ")", ")", ";", "list", "(", "$", "output", ",", "$", "...
Executes an external program. @param string[] $command The command as array. @return string[] The output of the command.
[ "Executes", "an", "external", "program", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L341-L362
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.extractPaths
private function extractPaths(string $mainJsFile): array { $command = [$this->nodePath, __DIR__.'/../../lib/extract_config.js', $mainJsFile]; $output = $this->execCommand($command); $config = json_decode(implode(PHP_EOL, $output), true); return [$config['baseUrl'], $config['paths']]; }
php
private function extractPaths(string $mainJsFile): array { $command = [$this->nodePath, __DIR__.'/../../lib/extract_config.js', $mainJsFile]; $output = $this->execCommand($command); $config = json_decode(implode(PHP_EOL, $output), true); return [$config['baseUrl'], $config['paths']]; }
[ "private", "function", "extractPaths", "(", "string", "$", "mainJsFile", ")", ":", "array", "{", "$", "command", "=", "[", "$", "this", "->", "nodePath", ",", "__DIR__", ".", "'/../../lib/extract_config.js'", ",", "$", "mainJsFile", "]", ";", "$", "output", ...
Reads the main.js file and returns baseUrl and paths. @param $mainJsFile @return array
[ "Reads", "the", "main", ".", "js", "file", "and", "returns", "baseUrl", "and", "paths", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L389-L398
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.getFullPathFromClassName
private function getFullPathFromClassName(string $className): string { $file_name = str_replace('\\', '/', $className).$this->extension; $full_path = $this->resourceDirFullPath.'/'.$file_name; return $full_path; }
php
private function getFullPathFromClassName(string $className): string { $file_name = str_replace('\\', '/', $className).$this->extension; $full_path = $this->resourceDirFullPath.'/'.$file_name; return $full_path; }
[ "private", "function", "getFullPathFromClassName", "(", "string", "$", "className", ")", ":", "string", "{", "$", "file_name", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "className", ")", ".", "$", "this", "->", "extension", ";", "$", "full_p...
Returns the full path of a ADM JavaScript file based on a PHP class name. @param string $className The PHP class name. @return string
[ "Returns", "the", "full", "path", "of", "a", "ADM", "JavaScript", "file", "based", "on", "a", "PHP", "class", "name", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L408-L414
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.getFullPathFromNamespace
private function getFullPathFromNamespace(string $namespace): string { $file_name = $namespace.$this->extension; $full_path = $this->resourceDirFullPath.'/'.$file_name; return $full_path; }
php
private function getFullPathFromNamespace(string $namespace): string { $file_name = $namespace.$this->extension; $full_path = $this->resourceDirFullPath.'/'.$file_name; return $full_path; }
[ "private", "function", "getFullPathFromNamespace", "(", "string", "$", "namespace", ")", ":", "string", "{", "$", "file_name", "=", "$", "namespace", ".", "$", "this", "->", "extension", ";", "$", "full_path", "=", "$", "this", "->", "resourceDirFullPath", "...
Returns the full path of a ADM JavaScript file based on a ADM namespace. @param string $namespace The ADM namespace. @return string
[ "Returns", "the", "full", "path", "of", "a", "ADM", "JavaScript", "file", "based", "on", "a", "ADM", "namespace", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L424-L430
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.getMainWithHashedPaths
private function getMainWithHashedPaths(string $realPath): string { $main_js_file = self::getMainJsFileName($realPath); // Read the main file. $js = file_get_contents($main_js_file); if ($js===false) $this->logError("Unable to read file '%s'.", $realPath); // Extract paths from main. preg_match('/^(.*paths:[^{]*)({[^}]*})(.*)$/sm', $js, $matches); if (!isset($matches[2])) $this->logError("Unable to find paths in '%s'.", $realPath); // @todo Remove from paths files already combined. // Lookup table as paths in requirejs.config, however, keys and values are flipped. $paths = []; // Replace aliases to paths with aliases to paths with hashes (i.e. paths to minimized files). list($base_url, $aliases) = $this->extractPaths($main_js_file); if (isset($base_url) && isset($paths)) { foreach ($aliases as $alias => $path) { $path_with_hash = $this->getPathInResourcesWithHash($base_url, $path); if (isset($path_with_hash)) { $paths[$this->removeJsExtension($path_with_hash)] = $alias; } } } // Add paths from modules that conform to ADM naming convention to paths with hashes (i.e. path to minimized files). foreach ($this->getResourcesInfo() as $info) { // @todo Skip *.main.js files. // Test JS file is not already in paths, e.g. 'jquery': 'jquery/jquery'. if (!isset($paths[$this->removeJsExtension($info['path_name_in_sources_with_hash'])])) { if (isset($info['path_name_in_sources'])) { $module = $this->getNamespaceFromResourceFilename($info['full_path_name']); $path_with_hash = $this->getNamespaceFromResourceFilename($info['full_path_name_with_hash']); $paths[$path_with_hash] = $module; } } } // Convert the paths to proper JS code. $matches[2] = json_encode(array_flip($paths), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); array_shift($matches); $js = implode('', $matches); return $js; }
php
private function getMainWithHashedPaths(string $realPath): string { $main_js_file = self::getMainJsFileName($realPath); // Read the main file. $js = file_get_contents($main_js_file); if ($js===false) $this->logError("Unable to read file '%s'.", $realPath); // Extract paths from main. preg_match('/^(.*paths:[^{]*)({[^}]*})(.*)$/sm', $js, $matches); if (!isset($matches[2])) $this->logError("Unable to find paths in '%s'.", $realPath); // @todo Remove from paths files already combined. // Lookup table as paths in requirejs.config, however, keys and values are flipped. $paths = []; // Replace aliases to paths with aliases to paths with hashes (i.e. paths to minimized files). list($base_url, $aliases) = $this->extractPaths($main_js_file); if (isset($base_url) && isset($paths)) { foreach ($aliases as $alias => $path) { $path_with_hash = $this->getPathInResourcesWithHash($base_url, $path); if (isset($path_with_hash)) { $paths[$this->removeJsExtension($path_with_hash)] = $alias; } } } // Add paths from modules that conform to ADM naming convention to paths with hashes (i.e. path to minimized files). foreach ($this->getResourcesInfo() as $info) { // @todo Skip *.main.js files. // Test JS file is not already in paths, e.g. 'jquery': 'jquery/jquery'. if (!isset($paths[$this->removeJsExtension($info['path_name_in_sources_with_hash'])])) { if (isset($info['path_name_in_sources'])) { $module = $this->getNamespaceFromResourceFilename($info['full_path_name']); $path_with_hash = $this->getNamespaceFromResourceFilename($info['full_path_name_with_hash']); $paths[$path_with_hash] = $module; } } } // Convert the paths to proper JS code. $matches[2] = json_encode(array_flip($paths), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); array_shift($matches); $js = implode('', $matches); return $js; }
[ "private", "function", "getMainWithHashedPaths", "(", "string", "$", "realPath", ")", ":", "string", "{", "$", "main_js_file", "=", "self", "::", "getMainJsFileName", "(", "$", "realPath", ")", ";", "// Read the main file.", "$", "js", "=", "file_get_contents", ...
Rewrites paths in requirejs.config. Adds path names from namespaces and aliases to filenames with hashes. @param string $realPath The filename of the main.js file. @return string
[ "Rewrites", "paths", "in", "requirejs", ".", "config", ".", "Adds", "path", "names", "from", "namespaces", "and", "aliases", "to", "filenames", "with", "hashes", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L440-L492
train
SetBased/php-abc-phing
src/Task/OptimizeJsTask.php
OptimizeJsTask.getNamespaceFromResourceFilename
private function getNamespaceFromResourceFilename(string $resourceFilename): string { $name = $this->getPathInResources($resourceFilename); // Remove resource dir from name. $len = strlen(trim($this->resourceDir, '/')); if ($len>0) { $name = substr($name, $len + 2); } // Remove extension. $parts = pathinfo($name); $name = substr($name, 0, -(strlen($parts['extension']) + 1)); return $name; }
php
private function getNamespaceFromResourceFilename(string $resourceFilename): string { $name = $this->getPathInResources($resourceFilename); // Remove resource dir from name. $len = strlen(trim($this->resourceDir, '/')); if ($len>0) { $name = substr($name, $len + 2); } // Remove extension. $parts = pathinfo($name); $name = substr($name, 0, -(strlen($parts['extension']) + 1)); return $name; }
[ "private", "function", "getNamespaceFromResourceFilename", "(", "string", "$", "resourceFilename", ")", ":", "string", "{", "$", "name", "=", "$", "this", "->", "getPathInResources", "(", "$", "resourceFilename", ")", ";", "// Remove resource dir from name.", "$", "...
Returns the namespace based on the name of a JavaScript file. @param string $resourceFilename The name of the JavaScript file. @return string
[ "Returns", "the", "namespace", "based", "on", "the", "name", "of", "a", "JavaScript", "file", "." ]
eb3d337ceafa7c1ae0caa5b70074dfea03d94017
https://github.com/SetBased/php-abc-phing/blob/eb3d337ceafa7c1ae0caa5b70074dfea03d94017/src/Task/OptimizeJsTask.php#L515-L531
train
agentmedia/phine-forms
src/Forms/Modules/Frontend/Form.php
Form.FetchFields
private function FetchFields($parent) { $child= $this->tree->FirstChildOf($parent); while ($child) { $this->HandleField($child); $this->FetchFields($child); $child = $this->tree->NextOf($child); } }
php
private function FetchFields($parent) { $child= $this->tree->FirstChildOf($parent); while ($child) { $this->HandleField($child); $this->FetchFields($child); $child = $this->tree->NextOf($child); } }
[ "private", "function", "FetchFields", "(", "$", "parent", ")", "{", "$", "child", "=", "$", "this", "->", "tree", "->", "FirstChildOf", "(", "$", "parent", ")", ";", "while", "(", "$", "child", ")", "{", "$", "this", "->", "HandleField", "(", "$", ...
Fetches all form field content elements and adds it to this form in an appropriate manner @param mixed $parent
[ "Fetches", "all", "form", "field", "content", "elements", "and", "adds", "it", "to", "this", "form", "in", "an", "appropriate", "manner" ]
cd7a92ea443756bef5885a9e8f59ad6b8d2771fc
https://github.com/agentmedia/phine-forms/blob/cd7a92ea443756bef5885a9e8f59ad6b8d2771fc/src/Forms/Modules/Frontend/Form.php#L77-L86
train
agentmedia/phine-forms
src/Forms/Modules/Frontend/Form.php
Form.SaveToTable
private function SaveToTable($table) { $sql = Access::SqlBuilder(); $fields = array(); $setList = null; foreach ($this->Elements()->GetElements() as $element) { $this->HandleElement($table, $element, $fields, $setList); } if ($setList) { Access::Connection()->ExecuteQuery($sql->Insert($sql->Table($table, $fields), $setList)); } }
php
private function SaveToTable($table) { $sql = Access::SqlBuilder(); $fields = array(); $setList = null; foreach ($this->Elements()->GetElements() as $element) { $this->HandleElement($table, $element, $fields, $setList); } if ($setList) { Access::Connection()->ExecuteQuery($sql->Insert($sql->Table($table, $fields), $setList)); } }
[ "private", "function", "SaveToTable", "(", "$", "table", ")", "{", "$", "sql", "=", "Access", "::", "SqlBuilder", "(", ")", ";", "$", "fields", "=", "array", "(", ")", ";", "$", "setList", "=", "null", ";", "foreach", "(", "$", "this", "->", "Eleme...
Stores the results in a database table @param string $table The table name
[ "Stores", "the", "results", "in", "a", "database", "table" ]
cd7a92ea443756bef5885a9e8f59ad6b8d2771fc
https://github.com/agentmedia/phine-forms/blob/cd7a92ea443756bef5885a9e8f59ad6b8d2771fc/src/Forms/Modules/Frontend/Form.php#L316-L329
train
Palmabit-IT/authenticator
src/Palmabit/Authentication/Helpers/FormHelper.php
FormHelper.prepareSentryPermissionInput
public function prepareSentryPermissionInput(array &$input, $operation, $field_name = "permissions") { $input[$field_name] = isset($input[$field_name]) ? [$input[$field_name] => $operation] : ''; }
php
public function prepareSentryPermissionInput(array &$input, $operation, $field_name = "permissions") { $input[$field_name] = isset($input[$field_name]) ? [$input[$field_name] => $operation] : ''; }
[ "public", "function", "prepareSentryPermissionInput", "(", "array", "&", "$", "input", ",", "$", "operation", ",", "$", "field_name", "=", "\"permissions\"", ")", "{", "$", "input", "[", "$", "field_name", "]", "=", "isset", "(", "$", "input", "[", "$", ...
Prepares permission for sentry given the input @param array $input @param $operation @param $field_name @return void
[ "Prepares", "permission", "for", "sentry", "given", "the", "input" ]
986cfc7e666e0e1b0312e518d586ec61b08cdb42
https://github.com/Palmabit-IT/authenticator/blob/986cfc7e666e0e1b0312e518d586ec61b08cdb42/src/Palmabit/Authentication/Helpers/FormHelper.php#L56-L58
train
monomelodies/ornament
src/Bitflag.php
Bitflag.jsonSerialize
public function jsonSerialize() { $ret = new StdClass; foreach ($this->map as $key => $value) { $ret->$key = (bool)($this->source & $value); } return $ret; }
php
public function jsonSerialize() { $ret = new StdClass; foreach ($this->map as $key => $value) { $ret->$key = (bool)($this->source & $value); } return $ret; }
[ "public", "function", "jsonSerialize", "(", ")", "{", "$", "ret", "=", "new", "StdClass", ";", "foreach", "(", "$", "this", "->", "map", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "ret", "->", "$", "key", "=", "(", "bool", ")", "(", "...
Export this bitflag as a Json object. All known bits are exported as properties with true or false depending on their status. @return StdClass A standard class suitable for json_encode.
[ "Export", "this", "bitflag", "as", "a", "Json", "object", ".", "All", "known", "bits", "are", "exported", "as", "properties", "with", "true", "or", "false", "depending", "on", "their", "status", "." ]
d7d070ad11f5731be141cf55c2756accaaf51402
https://github.com/monomelodies/ornament/blob/d7d070ad11f5731be141cf55c2756accaaf51402/src/Bitflag.php#L108-L115
train
joegreen88/zf1-components-base
src/Zend/Loader/StandardAutoloader.php
Zend_Loader_StandardAutoloader.autoload
public function autoload($class) { $isFallback = $this->isFallbackAutoloader(); if (false !== strpos($class, self::NS_SEPARATOR)) { if ($this->loadClass($class, self::LOAD_NS)) { return $class; } elseif ($isFallback) { return $this->loadClass($class, self::ACT_AS_FALLBACK); } return false; } if (false !== strpos($class, self::PREFIX_SEPARATOR)) { if ($this->loadClass($class, self::LOAD_PREFIX)) { return $class; } elseif ($isFallback) { return $this->loadClass($class, self::ACT_AS_FALLBACK); } return false; } if ($isFallback) { return $this->loadClass($class, self::ACT_AS_FALLBACK); } return false; }
php
public function autoload($class) { $isFallback = $this->isFallbackAutoloader(); if (false !== strpos($class, self::NS_SEPARATOR)) { if ($this->loadClass($class, self::LOAD_NS)) { return $class; } elseif ($isFallback) { return $this->loadClass($class, self::ACT_AS_FALLBACK); } return false; } if (false !== strpos($class, self::PREFIX_SEPARATOR)) { if ($this->loadClass($class, self::LOAD_PREFIX)) { return $class; } elseif ($isFallback) { return $this->loadClass($class, self::ACT_AS_FALLBACK); } return false; } if ($isFallback) { return $this->loadClass($class, self::ACT_AS_FALLBACK); } return false; }
[ "public", "function", "autoload", "(", "$", "class", ")", "{", "$", "isFallback", "=", "$", "this", "->", "isFallbackAutoloader", "(", ")", ";", "if", "(", "false", "!==", "strpos", "(", "$", "class", ",", "self", "::", "NS_SEPARATOR", ")", ")", "{", ...
Defined by Autoloadable; autoload a class @param string $class @return false|string
[ "Defined", "by", "Autoloadable", ";", "autoload", "a", "class" ]
d4591a2234c2db3094b54c08bcdc4303f7bf4819
https://github.com/joegreen88/zf1-components-base/blob/d4591a2234c2db3094b54c08bcdc4303f7bf4819/src/Zend/Loader/StandardAutoloader.php#L226-L249
train
joegreen88/zf1-components-base
src/Zend/Loader/StandardAutoloader.php
Zend_Loader_StandardAutoloader.transformClassNameToFilename
protected function transformClassNameToFilename($class, $directory) { // $class may contain a namespace portion, in which case we need // to preserve any underscores in that portion. $matches = array(); preg_match('/(?P<namespace>.+\\\)?(?P<class>[^\\\]+$)/', $class, $matches); $class = (isset($matches['class'])) ? $matches['class'] : ''; $namespace = (isset($matches['namespace'])) ? $matches['namespace'] : ''; return $directory . str_replace(self::NS_SEPARATOR, '/', $namespace) . str_replace(self::PREFIX_SEPARATOR, '/', $class) . '.php'; }
php
protected function transformClassNameToFilename($class, $directory) { // $class may contain a namespace portion, in which case we need // to preserve any underscores in that portion. $matches = array(); preg_match('/(?P<namespace>.+\\\)?(?P<class>[^\\\]+$)/', $class, $matches); $class = (isset($matches['class'])) ? $matches['class'] : ''; $namespace = (isset($matches['namespace'])) ? $matches['namespace'] : ''; return $directory . str_replace(self::NS_SEPARATOR, '/', $namespace) . str_replace(self::PREFIX_SEPARATOR, '/', $class) . '.php'; }
[ "protected", "function", "transformClassNameToFilename", "(", "$", "class", ",", "$", "directory", ")", "{", "// $class may contain a namespace portion, in which case we need", "// to preserve any underscores in that portion.", "$", "matches", "=", "array", "(", ")", ";", "p...
Transform the class name to a filename @param string $class @param string $directory @return string
[ "Transform", "the", "class", "name", "to", "a", "filename" ]
d4591a2234c2db3094b54c08bcdc4303f7bf4819
https://github.com/joegreen88/zf1-components-base/blob/d4591a2234c2db3094b54c08bcdc4303f7bf4819/src/Zend/Loader/StandardAutoloader.php#L283-L297
train
joegreen88/zf1-components-base
src/Zend/Loader/StandardAutoloader.php
Zend_Loader_StandardAutoloader.normalizeDirectory
protected function normalizeDirectory($directory) { $last = $directory[strlen($directory) - 1]; if (in_array($last, array('/', '\\'))) { $directory[strlen($directory) - 1] = DIRECTORY_SEPARATOR; return $directory; } $directory .= DIRECTORY_SEPARATOR; return $directory; }
php
protected function normalizeDirectory($directory) { $last = $directory[strlen($directory) - 1]; if (in_array($last, array('/', '\\'))) { $directory[strlen($directory) - 1] = DIRECTORY_SEPARATOR; return $directory; } $directory .= DIRECTORY_SEPARATOR; return $directory; }
[ "protected", "function", "normalizeDirectory", "(", "$", "directory", ")", "{", "$", "last", "=", "$", "directory", "[", "strlen", "(", "$", "directory", ")", "-", "1", "]", ";", "if", "(", "in_array", "(", "$", "last", ",", "array", "(", "'/'", ",",...
Normalize the directory to include a trailing directory separator @param string $directory @return string
[ "Normalize", "the", "directory", "to", "include", "a", "trailing", "directory", "separator" ]
d4591a2234c2db3094b54c08bcdc4303f7bf4819
https://github.com/joegreen88/zf1-components-base/blob/d4591a2234c2db3094b54c08bcdc4303f7bf4819/src/Zend/Loader/StandardAutoloader.php#L357-L366
train
glynnforrest/speedy-config
src/ConfigBuilder.php
ConfigBuilder.addResource
public function addResource($resource, $prefix = null) { $this->resources[] = [$resource, $prefix, true]; return $this; }
php
public function addResource($resource, $prefix = null) { $this->resources[] = [$resource, $prefix, true]; return $this; }
[ "public", "function", "addResource", "(", "$", "resource", ",", "$", "prefix", "=", "null", ")", "{", "$", "this", "->", "resources", "[", "]", "=", "[", "$", "resource", ",", "$", "prefix", ",", "true", "]", ";", "return", "$", "this", ";", "}" ]
Add a resource to load configuration values from. @param mixed $resource @param string|null $prefix The prefix to give the values, if any
[ "Add", "a", "resource", "to", "load", "configuration", "values", "from", "." ]
613995cd89b6212f2beca50f646a36a08e4dcaf7
https://github.com/glynnforrest/speedy-config/blob/613995cd89b6212f2beca50f646a36a08e4dcaf7/src/ConfigBuilder.php#L32-L37
train
glynnforrest/speedy-config
src/ConfigBuilder.php
ConfigBuilder.addOptionalResource
public function addOptionalResource($resource, $prefix = null) { $this->resources[] = [$resource, $prefix, false]; return $this; }
php
public function addOptionalResource($resource, $prefix = null) { $this->resources[] = [$resource, $prefix, false]; return $this; }
[ "public", "function", "addOptionalResource", "(", "$", "resource", ",", "$", "prefix", "=", "null", ")", "{", "$", "this", "->", "resources", "[", "]", "=", "[", "$", "resource", ",", "$", "prefix", ",", "false", "]", ";", "return", "$", "this", ";",...
Add an optional resource to load configuration values from. @param mixed $resource @param string|null $prefix The prefix to give the values, if any
[ "Add", "an", "optional", "resource", "to", "load", "configuration", "values", "from", "." ]
613995cd89b6212f2beca50f646a36a08e4dcaf7
https://github.com/glynnforrest/speedy-config/blob/613995cd89b6212f2beca50f646a36a08e4dcaf7/src/ConfigBuilder.php#L45-L50
train
glynnforrest/speedy-config
src/ConfigBuilder.php
ConfigBuilder.loadResource
protected function loadResource($resource, $required) { foreach ($this->loaders as $loader) { if (!$loader->supports($resource)) { continue; } try { return $loader->load($resource); } catch (ResourceNotFoundException $e) { if ($required) { throw $e; } return []; } } throw new ResourceException(sprintf('There is no configuration loader available to load the resource "%s"', $resource)); }
php
protected function loadResource($resource, $required) { foreach ($this->loaders as $loader) { if (!$loader->supports($resource)) { continue; } try { return $loader->load($resource); } catch (ResourceNotFoundException $e) { if ($required) { throw $e; } return []; } } throw new ResourceException(sprintf('There is no configuration loader available to load the resource "%s"', $resource)); }
[ "protected", "function", "loadResource", "(", "$", "resource", ",", "$", "required", ")", "{", "foreach", "(", "$", "this", "->", "loaders", "as", "$", "loader", ")", "{", "if", "(", "!", "$", "loader", "->", "supports", "(", "$", "resource", ")", ")...
Load a resource using a loader. The first loader that supports the resource will be used. @param mixed $resource @param bool $required @throws ResourceException @return array
[ "Load", "a", "resource", "using", "a", "loader", ".", "The", "first", "loader", "that", "supports", "the", "resource", "will", "be", "used", "." ]
613995cd89b6212f2beca50f646a36a08e4dcaf7
https://github.com/glynnforrest/speedy-config/blob/613995cd89b6212f2beca50f646a36a08e4dcaf7/src/ConfigBuilder.php#L63-L82
train
glynnforrest/speedy-config
src/ConfigBuilder.php
ConfigBuilder.getConfig
public function getConfig(Schema $schema = null) { if (!$schema) { $schema = new Schema(); } $config = new Config(); foreach ($this->resources as $resource) { $values = $this->loadResource($resource[0], $resource[2]); if (is_string($prefix = $resource[1])) { $values = [ $prefix => $values, ]; } $config->merge($values); } foreach ($this->processors as $processor) { $processor->onPostMerge($config, $schema); } return $config; }
php
public function getConfig(Schema $schema = null) { if (!$schema) { $schema = new Schema(); } $config = new Config(); foreach ($this->resources as $resource) { $values = $this->loadResource($resource[0], $resource[2]); if (is_string($prefix = $resource[1])) { $values = [ $prefix => $values, ]; } $config->merge($values); } foreach ($this->processors as $processor) { $processor->onPostMerge($config, $schema); } return $config; }
[ "public", "function", "getConfig", "(", "Schema", "$", "schema", "=", "null", ")", "{", "if", "(", "!", "$", "schema", ")", "{", "$", "schema", "=", "new", "Schema", "(", ")", ";", "}", "$", "config", "=", "new", "Config", "(", ")", ";", "foreach...
Get the resolved configuration. @return Config
[ "Get", "the", "resolved", "configuration", "." ]
613995cd89b6212f2beca50f646a36a08e4dcaf7
https://github.com/glynnforrest/speedy-config/blob/613995cd89b6212f2beca50f646a36a08e4dcaf7/src/ConfigBuilder.php#L89-L113
train
pletfix/core
src/Services/View.php
View.templateFile
private function templateFile($name) { $filename = $this->viewPath . '/' . str_replace('.', DIRECTORY_SEPARATOR, $name) . '.blade.php'; if (file_exists($filename)) { return $filename; } if (self::$manifest === null) { if (file_exists($this->pluginManifestOfViews)) { /** @noinspection PhpIncludeInspection */ self::$manifest = include $this->pluginManifestOfViews; } } return isset(self::$manifest[$name]) ? base_path(self::$manifest[$name]) : null; }
php
private function templateFile($name) { $filename = $this->viewPath . '/' . str_replace('.', DIRECTORY_SEPARATOR, $name) . '.blade.php'; if (file_exists($filename)) { return $filename; } if (self::$manifest === null) { if (file_exists($this->pluginManifestOfViews)) { /** @noinspection PhpIncludeInspection */ self::$manifest = include $this->pluginManifestOfViews; } } return isset(self::$manifest[$name]) ? base_path(self::$manifest[$name]) : null; }
[ "private", "function", "templateFile", "(", "$", "name", ")", "{", "$", "filename", "=", "$", "this", "->", "viewPath", ".", "'/'", ".", "str_replace", "(", "'.'", ",", "DIRECTORY_SEPARATOR", ",", "$", "name", ")", ".", "'.blade.php'", ";", "if", "(", ...
Get the full template filename by given view name. @param string $name Name of the view @return string
[ "Get", "the", "full", "template", "filename", "by", "given", "view", "name", "." ]
974945500f278eb6c1779832e08bbfca1007a7b3
https://github.com/pletfix/core/blob/974945500f278eb6c1779832e08bbfca1007a7b3/src/Services/View.php#L113-L128
train
pletfix/core
src/Services/View.php
View.isCacheUpToDate
private function isCacheUpToDate($cachedFile, $templateFile) { if (!file_exists($cachedFile)) { return false; } $cacheTime = filemtime($cachedFile); $templTime = filemtime($templateFile); return $cacheTime == $templTime; }
php
private function isCacheUpToDate($cachedFile, $templateFile) { if (!file_exists($cachedFile)) { return false; } $cacheTime = filemtime($cachedFile); $templTime = filemtime($templateFile); return $cacheTime == $templTime; }
[ "private", "function", "isCacheUpToDate", "(", "$", "cachedFile", ",", "$", "templateFile", ")", "{", "if", "(", "!", "file_exists", "(", "$", "cachedFile", ")", ")", "{", "return", "false", ";", "}", "$", "cacheTime", "=", "filemtime", "(", "$", "cached...
Determine if the cached file is up to date with the template. @param string $cachedFile @param string $templateFile @return bool
[ "Determine", "if", "the", "cached", "file", "is", "up", "to", "date", "with", "the", "template", "." ]
974945500f278eb6c1779832e08bbfca1007a7b3
https://github.com/pletfix/core/blob/974945500f278eb6c1779832e08bbfca1007a7b3/src/Services/View.php#L145-L155
train
pletfix/core
src/Services/View.php
View.saveFile
private function saveFile($file, $content, $time) { // create directory if not exists if (!is_dir($dir = dirname($file))) { // @codeCoverageIgnoreStart if (!make_dir($dir, 0775)) { throw new RuntimeException(sprintf('View Template Engine was not able to create directory "%s"', $dir)); // @codeCoverageIgnore } // @codeCoverageIgnoreEnd } // @codeCoverageIgnore // save file if (file_exists($file)) { unlink($file); // so we will to be the owner at the new file } if (file_put_contents($file, $content, LOCK_EX) === false) { throw new RuntimeException(sprintf('View Template Engine was not able to save file "%s"', $file)); // @codeCoverageIgnore } @chmod($file, 0664); // set file modification time if (!@touch($file, $time)) { throw new RuntimeException(sprintf('View Template Engine was not able to modify time of file "%s"', $file)); // @codeCoverageIgnore } }
php
private function saveFile($file, $content, $time) { // create directory if not exists if (!is_dir($dir = dirname($file))) { // @codeCoverageIgnoreStart if (!make_dir($dir, 0775)) { throw new RuntimeException(sprintf('View Template Engine was not able to create directory "%s"', $dir)); // @codeCoverageIgnore } // @codeCoverageIgnoreEnd } // @codeCoverageIgnore // save file if (file_exists($file)) { unlink($file); // so we will to be the owner at the new file } if (file_put_contents($file, $content, LOCK_EX) === false) { throw new RuntimeException(sprintf('View Template Engine was not able to save file "%s"', $file)); // @codeCoverageIgnore } @chmod($file, 0664); // set file modification time if (!@touch($file, $time)) { throw new RuntimeException(sprintf('View Template Engine was not able to modify time of file "%s"', $file)); // @codeCoverageIgnore } }
[ "private", "function", "saveFile", "(", "$", "file", ",", "$", "content", ",", "$", "time", ")", "{", "// create directory if not exists", "if", "(", "!", "is_dir", "(", "$", "dir", "=", "dirname", "(", "$", "file", ")", ")", ")", "{", "// @codeCoverageI...
Save the given content. @param string $file @param string $content @param int $time File modification time
[ "Save", "the", "given", "content", "." ]
974945500f278eb6c1779832e08bbfca1007a7b3
https://github.com/pletfix/core/blob/974945500f278eb6c1779832e08bbfca1007a7b3/src/Services/View.php#L164-L190
train
pletfix/core
src/Services/View.php
View.storeSection
private function storeSection($section, $content) { if (!isset($this->scope->sections[$section])) { $this->scope->sections[$section] = $content; } }
php
private function storeSection($section, $content) { if (!isset($this->scope->sections[$section])) { $this->scope->sections[$section] = $content; } }
[ "private", "function", "storeSection", "(", "$", "section", ",", "$", "content", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "scope", "->", "sections", "[", "$", "section", "]", ")", ")", "{", "$", "this", "->", "scope", "->", "secti...
Store section. @param string $section @param string $content
[ "Store", "section", "." ]
974945500f278eb6c1779832e08bbfca1007a7b3
https://github.com/pletfix/core/blob/974945500f278eb6c1779832e08bbfca1007a7b3/src/Services/View.php#L292-L297
train
Niirrty/Niirrty.IO
src/FileAccessException.php
FileAccessException.Read
public static function Read( string $file, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null ) : FileAccessException { return new FileAccessException ( $file, FileAccessException::ACCESS_READ, $message, $code, $previous ); }
php
public static function Read( string $file, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null ) : FileAccessException { return new FileAccessException ( $file, FileAccessException::ACCESS_READ, $message, $code, $previous ); }
[ "public", "static", "function", "Read", "(", "string", "$", "file", ",", "string", "$", "message", "=", "null", ",", "int", "$", "code", "=", "\\", "E_USER_ERROR", ",", "\\", "Throwable", "$", "previous", "=", "null", ")", ":", "FileAccessException", "{"...
Init's a new \Niirrty\IO\FileAccessException for file read mode. @param string $file The file where reading fails. @param string $message The optional error message. @param integer $code A optional error code (Defaults to \E_USER_ERROR) @param \Throwable $previous A Optional previous exception. @return \Niirrty\IO\FileAccessException
[ "Init", "s", "a", "new", "\\", "Niirrty", "\\", "IO", "\\", "FileAccessException", "for", "file", "read", "mode", "." ]
13a19de41d3002d76771b3f2c85a1158a863a78e
https://github.com/Niirrty/Niirrty.IO/blob/13a19de41d3002d76771b3f2c85a1158a863a78e/src/FileAccessException.php#L121-L134
train
Niirrty/Niirrty.IO
src/FileAccessException.php
FileAccessException.Write
public static function Write( string $file, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null ) : FileAccessException { return new FileAccessException ( $file, FileAccessException::ACCESS_WRITE, $message, $code, $previous ); }
php
public static function Write( string $file, string $message = null, int $code = \E_USER_ERROR, \Throwable $previous = null ) : FileAccessException { return new FileAccessException ( $file, FileAccessException::ACCESS_WRITE, $message, $code, $previous ); }
[ "public", "static", "function", "Write", "(", "string", "$", "file", ",", "string", "$", "message", "=", "null", ",", "int", "$", "code", "=", "\\", "E_USER_ERROR", ",", "\\", "Throwable", "$", "previous", "=", "null", ")", ":", "FileAccessException", "{...
Init's a new \UK\IO\FileAccessException for file write mode. @param string $file The file where reading fails. @param string $message The optional error message. @param integer $code A optional error code (Defaults to \E_USER_ERROR) @param \Throwable $previous A Optional previous exception. @return \Niirrty\IO\FileAccessException
[ "Init", "s", "a", "new", "\\", "UK", "\\", "IO", "\\", "FileAccessException", "for", "file", "write", "mode", "." ]
13a19de41d3002d76771b3f2c85a1158a863a78e
https://github.com/Niirrty/Niirrty.IO/blob/13a19de41d3002d76771b3f2c85a1158a863a78e/src/FileAccessException.php#L145-L158
train
jhorlima/wp-mocabonita
src/tools/MbAsset.php
MbAsset.runAssets
public function runAssets($pageSlug, $isShortcode = false) { $cssList = $this->css; $jsList = $this->js; MbWPActionHook::addActionCallback($this->getActionEnqueue(), function () use ($pageSlug, $cssList, $jsList) { foreach ($cssList as $i => $css) { wp_enqueue_style("style_mb_{$pageSlug}_{$i}", $css); } foreach ($jsList as $i => $js) { wp_enqueue_script("script_mb_{$pageSlug}_{$i}", $js['path'], [], $js['version'], $js['footer']); } }); if ($isShortcode) { MbWPActionHook::doAction($this->getActionEnqueue()); } }
php
public function runAssets($pageSlug, $isShortcode = false) { $cssList = $this->css; $jsList = $this->js; MbWPActionHook::addActionCallback($this->getActionEnqueue(), function () use ($pageSlug, $cssList, $jsList) { foreach ($cssList as $i => $css) { wp_enqueue_style("style_mb_{$pageSlug}_{$i}", $css); } foreach ($jsList as $i => $js) { wp_enqueue_script("script_mb_{$pageSlug}_{$i}", $js['path'], [], $js['version'], $js['footer']); } }); if ($isShortcode) { MbWPActionHook::doAction($this->getActionEnqueue()); } }
[ "public", "function", "runAssets", "(", "$", "pageSlug", ",", "$", "isShortcode", "=", "false", ")", "{", "$", "cssList", "=", "$", "this", "->", "css", ";", "$", "jsList", "=", "$", "this", "->", "js", ";", "MbWPActionHook", "::", "addActionCallback", ...
Send assets to wordpress @param string $pageSlug @param bool $isShortcode @return void
[ "Send", "assets", "to", "wordpress" ]
a864b40d5452bc9b892f02a6bb28c02639f25fa8
https://github.com/jhorlima/wp-mocabonita/blob/a864b40d5452bc9b892f02a6bb28c02639f25fa8/src/tools/MbAsset.php#L123-L141
train
jhorlima/wp-mocabonita
src/tools/MbAsset.php
MbAsset.autoEnqueue
protected function autoEnqueue() { $request = MocaBonita::getInstance()->getMbRequest(); if ($request->isLoginPage()) { $this->actionEnqueue = "login_enqueue_scripts"; } elseif ($request->isAdmin()) { $this->actionEnqueue = "admin_enqueue_scripts"; } else { $this->actionEnqueue = "wp_enqueue_scripts"; } }
php
protected function autoEnqueue() { $request = MocaBonita::getInstance()->getMbRequest(); if ($request->isLoginPage()) { $this->actionEnqueue = "login_enqueue_scripts"; } elseif ($request->isAdmin()) { $this->actionEnqueue = "admin_enqueue_scripts"; } else { $this->actionEnqueue = "wp_enqueue_scripts"; } }
[ "protected", "function", "autoEnqueue", "(", ")", "{", "$", "request", "=", "MocaBonita", "::", "getInstance", "(", ")", "->", "getMbRequest", "(", ")", ";", "if", "(", "$", "request", "->", "isLoginPage", "(", ")", ")", "{", "$", "this", "->", "action...
Auto Enqueue to wordpress @return void
[ "Auto", "Enqueue", "to", "wordpress" ]
a864b40d5452bc9b892f02a6bb28c02639f25fa8
https://github.com/jhorlima/wp-mocabonita/blob/a864b40d5452bc9b892f02a6bb28c02639f25fa8/src/tools/MbAsset.php#L162-L173
train
jhorlima/wp-mocabonita
src/tools/MbAsset.php
MbAsset.setActionEnqueue
public function setActionEnqueue($typePage) { switch ($typePage) { case 'admin' : $this->actionEnqueue = "admin_enqueue_scripts"; break; case 'login' : $this->actionEnqueue = "login_enqueue_scripts"; break; default : $this->actionEnqueue = "wp_enqueue_scripts"; break; } return $this; }
php
public function setActionEnqueue($typePage) { switch ($typePage) { case 'admin' : $this->actionEnqueue = "admin_enqueue_scripts"; break; case 'login' : $this->actionEnqueue = "login_enqueue_scripts"; break; default : $this->actionEnqueue = "wp_enqueue_scripts"; break; } return $this; }
[ "public", "function", "setActionEnqueue", "(", "$", "typePage", ")", "{", "switch", "(", "$", "typePage", ")", "{", "case", "'admin'", ":", "$", "this", "->", "actionEnqueue", "=", "\"admin_enqueue_scripts\"", ";", "break", ";", "case", "'login'", ":", "$", ...
Set a type of enqueue @param $typePage @return $this
[ "Set", "a", "type", "of", "enqueue" ]
a864b40d5452bc9b892f02a6bb28c02639f25fa8
https://github.com/jhorlima/wp-mocabonita/blob/a864b40d5452bc9b892f02a6bb28c02639f25fa8/src/tools/MbAsset.php#L182-L197
train
rawphp/communication-logger
src/Adapter/Factory/ConnectionFactory.php
ConnectionFactory.create
public function create($type, $host, $port, $database, $user, $password) { return new PDO( sprintf( '%s:host=%s;port=%s;dbname=%s', $type, $host, $port, $database ), $user, $password ); }
php
public function create($type, $host, $port, $database, $user, $password) { return new PDO( sprintf( '%s:host=%s;port=%s;dbname=%s', $type, $host, $port, $database ), $user, $password ); }
[ "public", "function", "create", "(", "$", "type", ",", "$", "host", ",", "$", "port", ",", "$", "database", ",", "$", "user", ",", "$", "password", ")", "{", "return", "new", "PDO", "(", "sprintf", "(", "'%s:host=%s;port=%s;dbname=%s'", ",", "$", "type...
Create PDO connection. @param string $type @param string $host @param string $port @param string $database @param string $user @param string $password @return PDO
[ "Create", "PDO", "connection", "." ]
df117bf65d55977d660b447b44b986b092423804
https://github.com/rawphp/communication-logger/blob/df117bf65d55977d660b447b44b986b092423804/src/Adapter/Factory/ConnectionFactory.php#L26-L39
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.addHeaders
public function addHeaders(array $headers) { foreach ($headers as $key => $value) { $header = NULL; //Handle Array of String based Headers if (is_numeric($key) && strpos($value,":") !== FALSE) { $arr = explode(":",$value,2); if (count($arr)==2){ $header = $arr[0]; $value = trim($arr[1]); } } else { $header = $key; } if ($header !== NULL){ $this->addHeader($header, $value); } } return $this; }
php
public function addHeaders(array $headers) { foreach ($headers as $key => $value) { $header = NULL; //Handle Array of String based Headers if (is_numeric($key) && strpos($value,":") !== FALSE) { $arr = explode(":",$value,2); if (count($arr)==2){ $header = $arr[0]; $value = trim($arr[1]); } } else { $header = $key; } if ($header !== NULL){ $this->addHeader($header, $value); } } return $this; }
[ "public", "function", "addHeaders", "(", "array", "$", "headers", ")", "{", "foreach", "(", "$", "headers", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "header", "=", "NULL", ";", "//Handle Array of String based Headers", "if", "(", "is_numeric", ...
Add multiple headers via an array @param array $headers @return $this
[ "Add", "multiple", "headers", "via", "an", "array" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L227-L247
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.compileOptions
private function compileOptions(){ $this->CurlOptions = array(); $this->configureHTTPMethod($this->method); $this->configureUrl($this->url); $this->configureBody($this->body); $this->configureHeaders($this->headers); $this->configureOptions($this->options); return $this; }
php
private function compileOptions(){ $this->CurlOptions = array(); $this->configureHTTPMethod($this->method); $this->configureUrl($this->url); $this->configureBody($this->body); $this->configureHeaders($this->headers); $this->configureOptions($this->options); return $this; }
[ "private", "function", "compileOptions", "(", ")", "{", "$", "this", "->", "CurlOptions", "=", "array", "(", ")", ";", "$", "this", "->", "configureHTTPMethod", "(", "$", "this", "->", "method", ")", ";", "$", "this", "->", "configureUrl", "(", "$", "t...
Actually initialize the cURL Resource and configure All options
[ "Actually", "initialize", "the", "cURL", "Resource", "and", "configure", "All", "options" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L458-L466
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.configureHTTPMethod
protected function configureHTTPMethod($method) { switch ($method) { case self::HTTP_GET: break; case self::HTTP_POST: return $this->addCurlOption(CURLOPT_POST, TRUE); default: return $this->addCurlOption(CURLOPT_CUSTOMREQUEST, $method); } return TRUE; }
php
protected function configureHTTPMethod($method) { switch ($method) { case self::HTTP_GET: break; case self::HTTP_POST: return $this->addCurlOption(CURLOPT_POST, TRUE); default: return $this->addCurlOption(CURLOPT_CUSTOMREQUEST, $method); } return TRUE; }
[ "protected", "function", "configureHTTPMethod", "(", "$", "method", ")", "{", "switch", "(", "$", "method", ")", "{", "case", "self", "::", "HTTP_GET", ":", "break", ";", "case", "self", "::", "HTTP_POST", ":", "return", "$", "this", "->", "addCurlOption",...
Configure the Curl Options based for a specific HTTP Method @param $method @return bool
[ "Configure", "the", "Curl", "Options", "based", "for", "a", "specific", "HTTP", "Method" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L473-L484
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.configureHeaders
protected function configureHeaders(array $headers){ $configuredHeaders = array(); foreach($headers as $header => $value){ $configuredHeaders[] = "$header: $value"; } return $this->addCurlOption(CURLOPT_HTTPHEADER, $configuredHeaders); }
php
protected function configureHeaders(array $headers){ $configuredHeaders = array(); foreach($headers as $header => $value){ $configuredHeaders[] = "$header: $value"; } return $this->addCurlOption(CURLOPT_HTTPHEADER, $configuredHeaders); }
[ "protected", "function", "configureHeaders", "(", "array", "$", "headers", ")", "{", "$", "configuredHeaders", "=", "array", "(", ")", ";", "foreach", "(", "$", "headers", "as", "$", "header", "=>", "$", "value", ")", "{", "$", "configuredHeaders", "[", ...
Configure the Headers by setting the CURLOPT_HTTPHEADER Option @param array $headers @return boolean
[ "Configure", "the", "Headers", "by", "setting", "the", "CURLOPT_HTTPHEADER", "Option" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L500-L506
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.configureBody
protected function configureBody($body){ $upload = $this->getUpload(); switch ($this->method) { case self::HTTP_GET: if (!$upload){ if (is_array($body) || is_object($body)){ $queryParams = http_build_query($body); } else { $queryParams = $body; } if (!empty($body)){ if (strpos($this->url, "?") === false) { $queryParams = "?".$queryParams; } else { $queryParams = "&".$queryParams; } return $this->configureUrl($this->url.$queryParams); } break; } default: if ($upload){ $this->addHeader('Content-Type','multipart/form-data'); } return $this->addCurlOption(CURLOPT_POSTFIELDS, $body); } }
php
protected function configureBody($body){ $upload = $this->getUpload(); switch ($this->method) { case self::HTTP_GET: if (!$upload){ if (is_array($body) || is_object($body)){ $queryParams = http_build_query($body); } else { $queryParams = $body; } if (!empty($body)){ if (strpos($this->url, "?") === false) { $queryParams = "?".$queryParams; } else { $queryParams = "&".$queryParams; } return $this->configureUrl($this->url.$queryParams); } break; } default: if ($upload){ $this->addHeader('Content-Type','multipart/form-data'); } return $this->addCurlOption(CURLOPT_POSTFIELDS, $body); } }
[ "protected", "function", "configureBody", "(", "$", "body", ")", "{", "$", "upload", "=", "$", "this", "->", "getUpload", "(", ")", ";", "switch", "(", "$", "this", "->", "method", ")", "{", "case", "self", "::", "HTTP_GET", ":", "if", "(", "!", "$...
Configure the Body to be set on the cURL Resource @param $body @return bool
[ "Configure", "the", "Body", "to", "be", "set", "on", "the", "cURL", "Resource" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L513-L539
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.init
protected function init() { $this->setMethod(static::$_DEFAULT_HTTP_METHOD); $this->setHeaders(static::$_DEFAULT_HEADERS); $this->setOptions(static::$_DEFAULT_OPTIONS); $this->body = NULL; $this->error = NULL; $this->status = self::STATUS_INIT; if (self::$_AUTO_INIT){ return $this->initCurl(); } return TRUE; }
php
protected function init() { $this->setMethod(static::$_DEFAULT_HTTP_METHOD); $this->setHeaders(static::$_DEFAULT_HEADERS); $this->setOptions(static::$_DEFAULT_OPTIONS); $this->body = NULL; $this->error = NULL; $this->status = self::STATUS_INIT; if (self::$_AUTO_INIT){ return $this->initCurl(); } return TRUE; }
[ "protected", "function", "init", "(", ")", "{", "$", "this", "->", "setMethod", "(", "static", "::", "$", "_DEFAULT_HTTP_METHOD", ")", ";", "$", "this", "->", "setHeaders", "(", "static", "::", "$", "_DEFAULT_HEADERS", ")", ";", "$", "this", "->", "setOp...
Initialize the Request Object, setting defaults for certain properties @return bool
[ "Initialize", "the", "Request", "Object", "setting", "defaults", "for", "certain", "properties" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L565-L577
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.configureCurl
private function configureCurl() { foreach($this->getCurlOptions() as $option => $value){ curl_setopt($this->CurlRequest,$option,$value); } return TRUE; }
php
private function configureCurl() { foreach($this->getCurlOptions() as $option => $value){ curl_setopt($this->CurlRequest,$option,$value); } return TRUE; }
[ "private", "function", "configureCurl", "(", ")", "{", "foreach", "(", "$", "this", "->", "getCurlOptions", "(", ")", "as", "$", "option", "=>", "$", "value", ")", "{", "curl_setopt", "(", "$", "this", "->", "CurlRequest", ",", "$", "option", ",", "$",...
Loop through CurlOptions and use curl_setopt to set options on cURL Resource @return $this
[ "Loop", "through", "CurlOptions", "and", "use", "curl_setopt", "to", "set", "options", "on", "cURL", "Resource" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L617-L623
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.executeCurl
private function executeCurl() { if ($this->initCurl()){ $this->configureCurl(); $this->CurlResponse = curl_exec($this->CurlRequest); $this->checkForError(); return TRUE; } return FALSE; }
php
private function executeCurl() { if ($this->initCurl()){ $this->configureCurl(); $this->CurlResponse = curl_exec($this->CurlRequest); $this->checkForError(); return TRUE; } return FALSE; }
[ "private", "function", "executeCurl", "(", ")", "{", "if", "(", "$", "this", "->", "initCurl", "(", ")", ")", "{", "$", "this", "->", "configureCurl", "(", ")", ";", "$", "this", "->", "CurlResponse", "=", "curl_exec", "(", "$", "this", "->", "CurlRe...
Execute Curl Resource and set the Curl Response @return $this
[ "Execute", "Curl", "Resource", "and", "set", "the", "Curl", "Response" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L629-L638
train
MichaelJ2324/OO-cURL
src/Request/AbstractRequest.php
AbstractRequest.checkForError
private function checkForError(){ $curlErrNo = curl_errno($this->CurlRequest); if ($curlErrNo !== CURLE_OK) { $this->error = TRUE; $this->CurlError = array( 'error' => $curlErrNo, 'error_message' => curl_error($this->CurlRequest) ); } }
php
private function checkForError(){ $curlErrNo = curl_errno($this->CurlRequest); if ($curlErrNo !== CURLE_OK) { $this->error = TRUE; $this->CurlError = array( 'error' => $curlErrNo, 'error_message' => curl_error($this->CurlRequest) ); } }
[ "private", "function", "checkForError", "(", ")", "{", "$", "curlErrNo", "=", "curl_errno", "(", "$", "this", "->", "CurlRequest", ")", ";", "if", "(", "$", "curlErrNo", "!==", "CURLE_OK", ")", "{", "$", "this", "->", "error", "=", "TRUE", ";", "$", ...
Check cURL Resource for Errors and add them to CurlError property if so
[ "Check", "cURL", "Resource", "for", "Errors", "and", "add", "them", "to", "CurlError", "property", "if", "so" ]
067a29f7e5fe1941d870819658952be6d4a1f9b4
https://github.com/MichaelJ2324/OO-cURL/blob/067a29f7e5fe1941d870819658952be6d4a1f9b4/src/Request/AbstractRequest.php#L643-L652
train
Novusvetus/AutoGitIgnore
src/GitIgnoreFile.php
GitIgnoreFile.setFile
public function setFile($filePath = '.gitignore') { $this->fileContent = array(); $this->afterLine = null; $this->filePath = $filePath; $this->checkPermissions(); $this->parse(); }
php
public function setFile($filePath = '.gitignore') { $this->fileContent = array(); $this->afterLine = null; $this->filePath = $filePath; $this->checkPermissions(); $this->parse(); }
[ "public", "function", "setFile", "(", "$", "filePath", "=", "'.gitignore'", ")", "{", "$", "this", "->", "fileContent", "=", "array", "(", ")", ";", "$", "this", "->", "afterLine", "=", "null", ";", "$", "this", "->", "filePath", "=", "$", "filePath", ...
Sets the file @param string $filePath The path to the .gitignore file @return self
[ "Sets", "the", "file" ]
b754f87c908cbf446787a1104ae12f76f3fad2c5
https://github.com/Novusvetus/AutoGitIgnore/blob/b754f87c908cbf446787a1104ae12f76f3fad2c5/src/GitIgnoreFile.php#L83-L90
train
Novusvetus/AutoGitIgnore
src/GitIgnoreFile.php
GitIgnoreFile.setLines
public function setLines($lines) { if (!is_array($lines)) { $this->lines = array( $lines ); } else { $this->lines = $lines; } return $this; }
php
public function setLines($lines) { if (!is_array($lines)) { $this->lines = array( $lines ); } else { $this->lines = $lines; } return $this; }
[ "public", "function", "setLines", "(", "$", "lines", ")", "{", "if", "(", "!", "is_array", "(", "$", "lines", ")", ")", "{", "$", "this", "->", "lines", "=", "array", "(", "$", "lines", ")", ";", "}", "else", "{", "$", "this", "->", "lines", "=...
Set the paths to write in .gitignore file @param array $lines @return self
[ "Set", "the", "paths", "to", "write", "in", ".", "gitignore", "file" ]
b754f87c908cbf446787a1104ae12f76f3fad2c5
https://github.com/Novusvetus/AutoGitIgnore/blob/b754f87c908cbf446787a1104ae12f76f3fad2c5/src/GitIgnoreFile.php#L177-L188
train
morrelinko/simple-photo
src/Toolbox/FileUtils.php
FileUtils.isAbsolute
public static function isAbsolute($path) { return ((isset($path[0]) ? ($path[0] == '/' || (ctype_alpha($path[0]) && ($path[1] == ':'))) : '') || (parse_url($path, PHP_URL_SCHEME) === true)) ? true : false; }
php
public static function isAbsolute($path) { return ((isset($path[0]) ? ($path[0] == '/' || (ctype_alpha($path[0]) && ($path[1] == ':'))) : '') || (parse_url($path, PHP_URL_SCHEME) === true)) ? true : false; }
[ "public", "static", "function", "isAbsolute", "(", "$", "path", ")", "{", "return", "(", "(", "isset", "(", "$", "path", "[", "0", "]", ")", "?", "(", "$", "path", "[", "0", "]", "==", "'/'", "||", "(", "ctype_alpha", "(", "$", "path", "[", "0"...
Checks if a path is an absolute path @param string $path @return bool
[ "Checks", "if", "a", "path", "is", "an", "absolute", "path" ]
be1fbe3139d32eb39e88cff93f847154bb6a8cb2
https://github.com/morrelinko/simple-photo/blob/be1fbe3139d32eb39e88cff93f847154bb6a8cb2/src/Toolbox/FileUtils.php#L74-L83
train
morrelinko/simple-photo
src/Toolbox/FileUtils.php
FileUtils.getMime
public static function getMime($file) { $fileInfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($fileInfo, $file); return empty($mime) ? : $mime; }
php
public static function getMime($file) { $fileInfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($fileInfo, $file); return empty($mime) ? : $mime; }
[ "public", "static", "function", "getMime", "(", "$", "file", ")", "{", "$", "fileInfo", "=", "finfo_open", "(", "FILEINFO_MIME_TYPE", ")", ";", "$", "mime", "=", "finfo_file", "(", "$", "fileInfo", ",", "$", "file", ")", ";", "return", "empty", "(", "$...
Gets the mime of a file @param string $file @return mixed
[ "Gets", "the", "mime", "of", "a", "file" ]
be1fbe3139d32eb39e88cff93f847154bb6a8cb2
https://github.com/morrelinko/simple-photo/blob/be1fbe3139d32eb39e88cff93f847154bb6a8cb2/src/Toolbox/FileUtils.php#L128-L134
train
ProgMiner/image-constructor
lib/TextSprite.php
TextSprite.render
public function render(): Image { $ftbbox = imageftbbox($this->fontSize, 0, $this->fontFile, $this->text, $this->extraInfo); $width = max($ftbbox[2] - $ftbbox[6], 1); $height = max($ftbbox[3] - $ftbbox[7], 1); // Getting an offset for the first symbol of text $ftbbox = imageftbbox($this->fontSize, 0, $this->fontFile, $this->text[0] ?? '', $this->extraInfo); $offset = $ftbbox[3] - $ftbbox[7]; $image = Utility::transparentImage($width, $height); imagefttext( $image->getResource(), $this->fontSize, 0, 0, $offset, $this->color->allocate($image->getResource()), $this->fontFile, $this->text, $this->extraInfo ); return $image; }
php
public function render(): Image { $ftbbox = imageftbbox($this->fontSize, 0, $this->fontFile, $this->text, $this->extraInfo); $width = max($ftbbox[2] - $ftbbox[6], 1); $height = max($ftbbox[3] - $ftbbox[7], 1); // Getting an offset for the first symbol of text $ftbbox = imageftbbox($this->fontSize, 0, $this->fontFile, $this->text[0] ?? '', $this->extraInfo); $offset = $ftbbox[3] - $ftbbox[7]; $image = Utility::transparentImage($width, $height); imagefttext( $image->getResource(), $this->fontSize, 0, 0, $offset, $this->color->allocate($image->getResource()), $this->fontFile, $this->text, $this->extraInfo ); return $image; }
[ "public", "function", "render", "(", ")", ":", "Image", "{", "$", "ftbbox", "=", "imageftbbox", "(", "$", "this", "->", "fontSize", ",", "0", ",", "$", "this", "->", "fontFile", ",", "$", "this", "->", "text", ",", "$", "this", "->", "extraInfo", "...
Renders object as an image. @return Image Image
[ "Renders", "object", "as", "an", "image", "." ]
a8d323f7c5f7d9ba131d6e0b4b52155c98dd240c
https://github.com/ProgMiner/image-constructor/blob/a8d323f7c5f7d9ba131d6e0b4b52155c98dd240c/lib/TextSprite.php#L75-L99
train
antarctica/laravel-token-blacklist
src/Antarctica/LaravelTokenBlacklist/Repository/TokenBlacklistRepositoryEloquent.php
TokenBlacklistRepositoryEloquent.check
public function check($token) { $blacklistedToken = $this->model ->where('user_id', $this->Token->getSubject($token)) ->where('expiry', '>', Carbon::now()) ->whereToken($token) ->first(); if ($blacklistedToken === null) { return true; } throw new BlacklistedTokenException(); }
php
public function check($token) { $blacklistedToken = $this->model ->where('user_id', $this->Token->getSubject($token)) ->where('expiry', '>', Carbon::now()) ->whereToken($token) ->first(); if ($blacklistedToken === null) { return true; } throw new BlacklistedTokenException(); }
[ "public", "function", "check", "(", "$", "token", ")", "{", "$", "blacklistedToken", "=", "$", "this", "->", "model", "->", "where", "(", "'user_id'", ",", "$", "this", "->", "Token", "->", "getSubject", "(", "$", "token", ")", ")", "->", "where", "(...
Check if a given token is considered blacklisted TODO: Use export() method @param $token @return bool @throws BlacklistedTokenException
[ "Check", "if", "a", "given", "token", "is", "considered", "blacklisted" ]
69d9f499ec5569d139233b6c6c9eefdf86a62e9d
https://github.com/antarctica/laravel-token-blacklist/blob/69d9f499ec5569d139233b6c6c9eefdf86a62e9d/src/Antarctica/LaravelTokenBlacklist/Repository/TokenBlacklistRepositoryEloquent.php#L96-L109
train
antarctica/laravel-token-blacklist
src/Antarctica/LaravelTokenBlacklist/Repository/TokenBlacklistRepositoryEloquent.php
TokenBlacklistRepositoryEloquent.findByToken
public function findByToken($token) { $blacklistedToken = $this->model->whereToken($token)->first(); if ($blacklistedToken === null) { throw new ModelNotFoundException(); } return $blacklistedToken->toArray(); }
php
public function findByToken($token) { $blacklistedToken = $this->model->whereToken($token)->first(); if ($blacklistedToken === null) { throw new ModelNotFoundException(); } return $blacklistedToken->toArray(); }
[ "public", "function", "findByToken", "(", "$", "token", ")", "{", "$", "blacklistedToken", "=", "$", "this", "->", "model", "->", "whereToken", "(", "$", "token", ")", "->", "first", "(", ")", ";", "if", "(", "$", "blacklistedToken", "===", "null", ")"...
Try to find a blacklisted token entity by its associated token TODO: Use export() method @param string $token @return array
[ "Try", "to", "find", "a", "blacklisted", "token", "entity", "by", "its", "associated", "token" ]
69d9f499ec5569d139233b6c6c9eefdf86a62e9d
https://github.com/antarctica/laravel-token-blacklist/blob/69d9f499ec5569d139233b6c6c9eefdf86a62e9d/src/Antarctica/LaravelTokenBlacklist/Repository/TokenBlacklistRepositoryEloquent.php#L119-L129
train
antarctica/laravel-token-blacklist
src/Antarctica/LaravelTokenBlacklist/Repository/TokenBlacklistRepositoryEloquent.php
TokenBlacklistRepositoryEloquent.findAllExpired
public function findAllExpired() { $expiredBlacklistedTokens = $this->model->where('expiry', '<', Carbon::now())->get(); return $expiredBlacklistedTokens->toArray(); }
php
public function findAllExpired() { $expiredBlacklistedTokens = $this->model->where('expiry', '<', Carbon::now())->get(); return $expiredBlacklistedTokens->toArray(); }
[ "public", "function", "findAllExpired", "(", ")", "{", "$", "expiredBlacklistedTokens", "=", "$", "this", "->", "model", "->", "where", "(", "'expiry'", ",", "'<'", ",", "Carbon", "::", "now", "(", ")", ")", "->", "get", "(", ")", ";", "return", "$", ...
Find all blacklisted tokens that have naturally expired, and so no longer need to be tracked TODO: Use export() method Returns any blacklisted tokens that will have expired naturally and so no longer need to be considered. @return array
[ "Find", "all", "blacklisted", "tokens", "that", "have", "naturally", "expired", "and", "so", "no", "longer", "need", "to", "be", "tracked" ]
69d9f499ec5569d139233b6c6c9eefdf86a62e9d
https://github.com/antarctica/laravel-token-blacklist/blob/69d9f499ec5569d139233b6c6c9eefdf86a62e9d/src/Antarctica/LaravelTokenBlacklist/Repository/TokenBlacklistRepositoryEloquent.php#L140-L145
train
antarctica/laravel-token-blacklist
src/Antarctica/LaravelTokenBlacklist/Repository/TokenBlacklistRepositoryEloquent.php
TokenBlacklistRepositoryEloquent.deleteAllExpired
public function deleteAllExpired() { $expiredBlacklistedTokens = $this->findAllExpired(); foreach ($expiredBlacklistedTokens as $expiredBlacklistedToken) { $this->delete($expiredBlacklistedToken['id']); } }
php
public function deleteAllExpired() { $expiredBlacklistedTokens = $this->findAllExpired(); foreach ($expiredBlacklistedTokens as $expiredBlacklistedToken) { $this->delete($expiredBlacklistedToken['id']); } }
[ "public", "function", "deleteAllExpired", "(", ")", "{", "$", "expiredBlacklistedTokens", "=", "$", "this", "->", "findAllExpired", "(", ")", ";", "foreach", "(", "$", "expiredBlacklistedTokens", "as", "$", "expiredBlacklistedToken", ")", "{", "$", "this", "->",...
Delete all blacklisted token entities where the associated token has naturally expired, and so no longer needs to be tracked
[ "Delete", "all", "blacklisted", "token", "entities", "where", "the", "associated", "token", "has", "naturally", "expired", "and", "so", "no", "longer", "needs", "to", "be", "tracked" ]
69d9f499ec5569d139233b6c6c9eefdf86a62e9d
https://github.com/antarctica/laravel-token-blacklist/blob/69d9f499ec5569d139233b6c6c9eefdf86a62e9d/src/Antarctica/LaravelTokenBlacklist/Repository/TokenBlacklistRepositoryEloquent.php#L150-L158
train
slickframework/orm
src/Repository/QueryObject/QueryObject.php
QueryObject.updateCollection
public function updateCollection(EntityChangeEventInterface $event) { $collection = $event->getCollection(); if ($collection->getId()) { $collectionMap = $this->getCollectionsMap(); $collectionMap ->set($collection->getId(), $collection); } }
php
public function updateCollection(EntityChangeEventInterface $event) { $collection = $event->getCollection(); if ($collection->getId()) { $collectionMap = $this->getCollectionsMap(); $collectionMap ->set($collection->getId(), $collection); } }
[ "public", "function", "updateCollection", "(", "EntityChangeEventInterface", "$", "event", ")", "{", "$", "collection", "=", "$", "event", "->", "getCollection", "(", ")", ";", "if", "(", "$", "collection", "->", "getId", "(", ")", ")", "{", "$", "collecti...
Handles collection add event and updates the cache @param EntityChangeEventInterface $event
[ "Handles", "collection", "add", "event", "and", "updates", "the", "cache" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Repository/QueryObject/QueryObject.php#L92-L100
train
slickframework/orm
src/Repository/QueryObject/QueryObject.php
QueryObject.query
protected function query(Select $sql) { $cid = $this->getId($sql); $collection = $this->repository ->getCollectionsMap() ->get($cid, false); if (false === $collection) { $collection = $this->getCollection($sql, $cid); } return $collection; }
php
protected function query(Select $sql) { $cid = $this->getId($sql); $collection = $this->repository ->getCollectionsMap() ->get($cid, false); if (false === $collection) { $collection = $this->getCollection($sql, $cid); } return $collection; }
[ "protected", "function", "query", "(", "Select", "$", "sql", ")", "{", "$", "cid", "=", "$", "this", "->", "getId", "(", "$", "sql", ")", ";", "$", "collection", "=", "$", "this", "->", "repository", "->", "getCollectionsMap", "(", ")", "->", "get", ...
Execute provided query @param Select $sql @return EntityCollectionInterface
[ "Execute", "provided", "query" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Repository/QueryObject/QueryObject.php#L109-L121
train
slickframework/orm
src/Repository/QueryObject/QueryObject.php
QueryObject.getCollection
protected function getCollection(Select $sql, $cid) { $this->triggerBeforeSelect( $sql, $this->getRepository()->getEntityDescriptor() ); $data = $this->adapter->query($sql, $sql->getParameters()); $collection = $this->repository->getEntityMapper() ->createFrom($data); $this->triggerAfterSelect( $data, $collection ); $this->registerEventsTo($collection, $cid); $this->getCollectionsMap()->set($cid, $collection); $this->updateIdentityMap($collection); return $collection; }
php
protected function getCollection(Select $sql, $cid) { $this->triggerBeforeSelect( $sql, $this->getRepository()->getEntityDescriptor() ); $data = $this->adapter->query($sql, $sql->getParameters()); $collection = $this->repository->getEntityMapper() ->createFrom($data); $this->triggerAfterSelect( $data, $collection ); $this->registerEventsTo($collection, $cid); $this->getCollectionsMap()->set($cid, $collection); $this->updateIdentityMap($collection); return $collection; }
[ "protected", "function", "getCollection", "(", "Select", "$", "sql", ",", "$", "cid", ")", "{", "$", "this", "->", "triggerBeforeSelect", "(", "$", "sql", ",", "$", "this", "->", "getRepository", "(", ")", "->", "getEntityDescriptor", "(", ")", ")", ";",...
Executes the provided query @param Select $sql @param string $cid @return EntityCollectionInterface
[ "Executes", "the", "provided", "query" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Repository/QueryObject/QueryObject.php#L131-L149
train
slickframework/orm
src/Repository/QueryObject/QueryObject.php
QueryObject.getCollectionsMap
protected function getCollectionsMap() { if (null == $this->collectionsMap) { $this->collectionsMap = $this->repository->getCollectionsMap(); } return $this->collectionsMap; }
php
protected function getCollectionsMap() { if (null == $this->collectionsMap) { $this->collectionsMap = $this->repository->getCollectionsMap(); } return $this->collectionsMap; }
[ "protected", "function", "getCollectionsMap", "(", ")", "{", "if", "(", "null", "==", "$", "this", "->", "collectionsMap", ")", "{", "$", "this", "->", "collectionsMap", "=", "$", "this", "->", "repository", "->", "getCollectionsMap", "(", ")", ";", "}", ...
Returns the collections map storage @return CollectionsMap|\Slick\Orm\Entity\CollectionsMapInterface
[ "Returns", "the", "collections", "map", "storage" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Repository/QueryObject/QueryObject.php#L156-L162
train
slickframework/orm
src/Repository/QueryObject/QueryObject.php
QueryObject.registerEventsTo
protected function registerEventsTo(EntityCollection $collection, $cid) { $collection->setId($cid); $collection->getEmitter() ->addListener( EntityAdded::ACTION_ADD, [$this, 'updateCollection'] ); $collection->getEmitter() ->addListener( EntityRemoved::ACTION_REMOVE, [$this, 'updateCollection'] ); $entity = $this->repository->getEntityDescriptor()->className(); Orm::addListener( $entity, Delete::ACTION_AFTER_DELETE, function (Delete $event) use ($collection) { $collection->remove($event->getEntity()); }, EmitterInterface::P_HIGH ); return $this; }
php
protected function registerEventsTo(EntityCollection $collection, $cid) { $collection->setId($cid); $collection->getEmitter() ->addListener( EntityAdded::ACTION_ADD, [$this, 'updateCollection'] ); $collection->getEmitter() ->addListener( EntityRemoved::ACTION_REMOVE, [$this, 'updateCollection'] ); $entity = $this->repository->getEntityDescriptor()->className(); Orm::addListener( $entity, Delete::ACTION_AFTER_DELETE, function (Delete $event) use ($collection) { $collection->remove($event->getEntity()); }, EmitterInterface::P_HIGH ); return $this; }
[ "protected", "function", "registerEventsTo", "(", "EntityCollection", "$", "collection", ",", "$", "cid", ")", "{", "$", "collection", "->", "setId", "(", "$", "cid", ")", ";", "$", "collection", "->", "getEmitter", "(", ")", "->", "addListener", "(", "Ent...
Register entity events listeners for the provided collection @param EntityCollection $collection @param string $cid @return self
[ "Register", "entity", "events", "listeners", "for", "the", "provided", "collection" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Repository/QueryObject/QueryObject.php#L172-L195
train
slickframework/orm
src/Repository/QueryObject/QueryObject.php
QueryObject.getId
protected function getId(Select $query) { $str = $query->getQueryString(); $search = array_keys($query->getParameters()); $values = array_values($query->getParameters()); return str_replace($search, $values, $str); }
php
protected function getId(Select $query) { $str = $query->getQueryString(); $search = array_keys($query->getParameters()); $values = array_values($query->getParameters()); return str_replace($search, $values, $str); }
[ "protected", "function", "getId", "(", "Select", "$", "query", ")", "{", "$", "str", "=", "$", "query", "->", "getQueryString", "(", ")", ";", "$", "search", "=", "array_keys", "(", "$", "query", "->", "getParameters", "(", ")", ")", ";", "$", "value...
Gets the id for this query @param Select $query @return string
[ "Gets", "the", "id", "for", "this", "query" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Repository/QueryObject/QueryObject.php#L204-L210
train
slickframework/orm
src/Repository/QueryObject/QueryObject.php
QueryObject.updateIdentityMap
protected function updateIdentityMap(EntityCollection $collection) { if ($collection->isEmpty()) { return $this; } foreach ($collection as $entity) { $this->repository->getIdentityMap()->set($entity); } return $this; }
php
protected function updateIdentityMap(EntityCollection $collection) { if ($collection->isEmpty()) { return $this; } foreach ($collection as $entity) { $this->repository->getIdentityMap()->set($entity); } return $this; }
[ "protected", "function", "updateIdentityMap", "(", "EntityCollection", "$", "collection", ")", "{", "if", "(", "$", "collection", "->", "isEmpty", "(", ")", ")", "{", "return", "$", "this", ";", "}", "foreach", "(", "$", "collection", "as", "$", "entity", ...
Registers every entity in collection to the repository identity map @param EntityCollection $collection @return self
[ "Registers", "every", "entity", "in", "collection", "to", "the", "repository", "identity", "map" ]
c5c782f5e3a46cdc6c934eda4411cb9edc48f969
https://github.com/slickframework/orm/blob/c5c782f5e3a46cdc6c934eda4411cb9edc48f969/src/Repository/QueryObject/QueryObject.php#L219-L230
train
chigix/chiji-frontend
src/Project/SourceRoad.php
SourceRoad.resourcePathMatch
protected function resourcePathMatch(File $file) { $source_dirpath = str_replace('#', '\#', $this->sourceDir->getAbsolutePath()); $source_dirpath = str_replace('[', '\[', $source_dirpath); $source_dirpath = str_replace(']', '\]', $source_dirpath); $source_dirpath = str_replace('(', '\(', $source_dirpath); $source_dirpath = str_replace(')', '\)', $source_dirpath); return preg_match('#^' . $source_dirpath . '/' . $this->getRegex() . '#', $file->getAbsolutePath()) ? TRUE : FALSE; }
php
protected function resourcePathMatch(File $file) { $source_dirpath = str_replace('#', '\#', $this->sourceDir->getAbsolutePath()); $source_dirpath = str_replace('[', '\[', $source_dirpath); $source_dirpath = str_replace(']', '\]', $source_dirpath); $source_dirpath = str_replace('(', '\(', $source_dirpath); $source_dirpath = str_replace(')', '\)', $source_dirpath); return preg_match('#^' . $source_dirpath . '/' . $this->getRegex() . '#', $file->getAbsolutePath()) ? TRUE : FALSE; }
[ "protected", "function", "resourcePathMatch", "(", "File", "$", "file", ")", "{", "$", "source_dirpath", "=", "str_replace", "(", "'#'", ",", "'\\#'", ",", "$", "this", "->", "sourceDir", "->", "getAbsolutePath", "(", ")", ")", ";", "$", "source_dirpath", ...
Check if the resource match this road @param File $file @return boolean
[ "Check", "if", "the", "resource", "match", "this", "road" ]
5407f98c21ee99f8bbef43c97a231c0f81ed3e74
https://github.com/chigix/chiji-frontend/blob/5407f98c21ee99f8bbef43c97a231c0f81ed3e74/src/Project/SourceRoad.php#L110-L117
train
chigix/chiji-frontend
src/Project/SourceRoad.php
SourceRoad.releaseResource
public function releaseResource(AbstractResourceFile $resource) { if (is_null($this->getReleaseDir())) { throw new Exception("ERROR: RELEASE DIR IS NULL: " . $resource->getRealPath()); } if (!$this->getReleaseDir()->exists()) { $this->getReleaseDir()->mkdirs(); } $release_file = $this->makeReleaseFile($resource); $release_dir = $release_file->getAbsoluteFile()->getParentFile(); if (!$release_dir->exists()) { if (!$release_dir->mkdirs()) { throw new FileWriteErrorException("The directory '" . $release_dir->getAbsolutePath() . "' create fails."); } } \file_put_contents($release_file->getAbsolutePath(), $resource->getFileContents()); }
php
public function releaseResource(AbstractResourceFile $resource) { if (is_null($this->getReleaseDir())) { throw new Exception("ERROR: RELEASE DIR IS NULL: " . $resource->getRealPath()); } if (!$this->getReleaseDir()->exists()) { $this->getReleaseDir()->mkdirs(); } $release_file = $this->makeReleaseFile($resource); $release_dir = $release_file->getAbsoluteFile()->getParentFile(); if (!$release_dir->exists()) { if (!$release_dir->mkdirs()) { throw new FileWriteErrorException("The directory '" . $release_dir->getAbsolutePath() . "' create fails."); } } \file_put_contents($release_file->getAbsolutePath(), $resource->getFileContents()); }
[ "public", "function", "releaseResource", "(", "AbstractResourceFile", "$", "resource", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "getReleaseDir", "(", ")", ")", ")", "{", "throw", "new", "Exception", "(", "\"ERROR: RELEASE DIR IS NULL: \"", ".", ...
Execute the release action for the resource @param AbstractResourceFile $resource The source file to release. @throws FileWriteErrorException
[ "Execute", "the", "release", "action", "for", "the", "resource" ]
5407f98c21ee99f8bbef43c97a231c0f81ed3e74
https://github.com/chigix/chiji-frontend/blob/5407f98c21ee99f8bbef43c97a231c0f81ed3e74/src/Project/SourceRoad.php#L185-L200
train
chigix/chiji-frontend
src/Project/SourceRoad.php
SourceRoad.makeReleaseFile
public final function makeReleaseFile(AbstractResourceFile $resource) { if (!isset($this->__release__file__map[$resource->getMemberId()])) { $this->__release__file__map[$resource->getMemberId()] = new File($this->makeReleaseRelativePath($resource), $this->getReleaseDir()->getAbsolutePath()); } return $this->__release__file__map[$resource->getMemberId()]; }
php
public final function makeReleaseFile(AbstractResourceFile $resource) { if (!isset($this->__release__file__map[$resource->getMemberId()])) { $this->__release__file__map[$resource->getMemberId()] = new File($this->makeReleaseRelativePath($resource), $this->getReleaseDir()->getAbsolutePath()); } return $this->__release__file__map[$resource->getMemberId()]; }
[ "public", "final", "function", "makeReleaseFile", "(", "AbstractResourceFile", "$", "resource", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "__release__file__map", "[", "$", "resource", "->", "getMemberId", "(", ")", "]", ")", ")", "{", "$",...
Generate the file object to release for the given resource. @param AbstractResourceFile $resource @return File
[ "Generate", "the", "file", "object", "to", "release", "for", "the", "given", "resource", "." ]
5407f98c21ee99f8bbef43c97a231c0f81ed3e74
https://github.com/chigix/chiji-frontend/blob/5407f98c21ee99f8bbef43c97a231c0f81ed3e74/src/Project/SourceRoad.php#L210-L215
train
chigix/chiji-frontend
src/Project/SourceRoad.php
SourceRoad.getParentProject
public final function getParentProject() { if (\is_null($this->__parent__project)) { $result = ProjectUtil::searchRelativeProject($this); if (\count($result) < 1) { throw new ProjectMemberNotFoundException("SOURCE ROAD NOT FOUND"); } $this->__parent__project = $result[0]; } return $this->__parent__project; }
php
public final function getParentProject() { if (\is_null($this->__parent__project)) { $result = ProjectUtil::searchRelativeProject($this); if (\count($result) < 1) { throw new ProjectMemberNotFoundException("SOURCE ROAD NOT FOUND"); } $this->__parent__project = $result[0]; } return $this->__parent__project; }
[ "public", "final", "function", "getParentProject", "(", ")", "{", "if", "(", "\\", "is_null", "(", "$", "this", "->", "__parent__project", ")", ")", "{", "$", "result", "=", "ProjectUtil", "::", "searchRelativeProject", "(", "$", "this", ")", ";", "if", ...
Gets the parent of this annotation. @return Project The parent project of this annotation.
[ "Gets", "the", "parent", "of", "this", "annotation", "." ]
5407f98c21ee99f8bbef43c97a231c0f81ed3e74
https://github.com/chigix/chiji-frontend/blob/5407f98c21ee99f8bbef43c97a231c0f81ed3e74/src/Project/SourceRoad.php#L250-L259
train
droath/console-form
src/Field/Field.php
Field.setCondition
public function setCondition($field_name, $value, $operation = '=') { $this->condition[$field_name] = [ 'value' => $value, 'operation' => $operation ]; return $this; }
php
public function setCondition($field_name, $value, $operation = '=') { $this->condition[$field_name] = [ 'value' => $value, 'operation' => $operation ]; return $this; }
[ "public", "function", "setCondition", "(", "$", "field_name", ",", "$", "value", ",", "$", "operation", "=", "'='", ")", "{", "$", "this", "->", "condition", "[", "$", "field_name", "]", "=", "[", "'value'", "=>", "$", "value", ",", "'operation'", "=>"...
Set field conditions. @param string $field_name The field name. Use dot notation if you need to check conditions that are nested. @param string $value The field value that needs to be met.
[ "Set", "field", "conditions", "." ]
0fb43fdebd1f685779c9fffea43a0dccd4ebe14a
https://github.com/droath/console-form/blob/0fb43fdebd1f685779c9fffea43a0dccd4ebe14a/src/Field/Field.php#L282-L290
train
droath/console-form
src/Field/Field.php
Field.asQuestion
public function asQuestion() { $instance = $this->questionClassInstance() ->setMaxAttempts($this->maxAttempt); // Set question instance hidden if defined by the field. if ($this->hidden) { $instance->setHidden(true); } // Set validation callback if field is required. if ($this->isRequire()) { $this->setValidation(function ($answer) { if ($answer == '' && $this->dataType() !== 'boolean') { throw new \Exception('Field is required.'); } }); } // Set question instance validator callback. $instance->setValidator(function ($answer) { // Iterate over all field validation callbacks. foreach ($this->validation as $callback) { if (!is_callable($callback)) { continue; } $callback($answer); } return $answer; }); // Set question normalizer based on the field normalizer. If a default // normalizer is being set from the question class then setting the // normalizer will trump it's execution, as only one normalizer can be // set per question instance. if (isset($this->normalizer) && is_callable($this->normalizer)) { $instance->setNormalizer($this->normalizer); } return $instance; }
php
public function asQuestion() { $instance = $this->questionClassInstance() ->setMaxAttempts($this->maxAttempt); // Set question instance hidden if defined by the field. if ($this->hidden) { $instance->setHidden(true); } // Set validation callback if field is required. if ($this->isRequire()) { $this->setValidation(function ($answer) { if ($answer == '' && $this->dataType() !== 'boolean') { throw new \Exception('Field is required.'); } }); } // Set question instance validator callback. $instance->setValidator(function ($answer) { // Iterate over all field validation callbacks. foreach ($this->validation as $callback) { if (!is_callable($callback)) { continue; } $callback($answer); } return $answer; }); // Set question normalizer based on the field normalizer. If a default // normalizer is being set from the question class then setting the // normalizer will trump it's execution, as only one normalizer can be // set per question instance. if (isset($this->normalizer) && is_callable($this->normalizer)) { $instance->setNormalizer($this->normalizer); } return $instance; }
[ "public", "function", "asQuestion", "(", ")", "{", "$", "instance", "=", "$", "this", "->", "questionClassInstance", "(", ")", "->", "setMaxAttempts", "(", "$", "this", "->", "maxAttempt", ")", ";", "// Set question instance hidden if defined by the field.", "if", ...
Field as question instance. @return \Symfony\Component\Console\Question\Question
[ "Field", "as", "question", "instance", "." ]
0fb43fdebd1f685779c9fffea43a0dccd4ebe14a
https://github.com/droath/console-form/blob/0fb43fdebd1f685779c9fffea43a0dccd4ebe14a/src/Field/Field.php#L344-L389
train
droath/console-form
src/Field/Field.php
Field.questionClassInstance
protected function questionClassInstance() { $classname = $this->questionClass(); if (!class_exists($classname)) { throw new \Exception('Invalid question class.'); } $instance = (new \ReflectionClass($classname)) ->newInstanceArgs($this->questionClassArgs()); if (!$instance instanceof \Symfony\Component\Console\Question\Question) { throw new \Exception('Invalid question class instance'); } return $instance; }
php
protected function questionClassInstance() { $classname = $this->questionClass(); if (!class_exists($classname)) { throw new \Exception('Invalid question class.'); } $instance = (new \ReflectionClass($classname)) ->newInstanceArgs($this->questionClassArgs()); if (!$instance instanceof \Symfony\Component\Console\Question\Question) { throw new \Exception('Invalid question class instance'); } return $instance; }
[ "protected", "function", "questionClassInstance", "(", ")", "{", "$", "classname", "=", "$", "this", "->", "questionClass", "(", ")", ";", "if", "(", "!", "class_exists", "(", "$", "classname", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Inv...
Question class instance. @return \Symfony\Component\Console\Question\Question An instantiated question class.
[ "Question", "class", "instance", "." ]
0fb43fdebd1f685779c9fffea43a0dccd4ebe14a
https://github.com/droath/console-form/blob/0fb43fdebd1f685779c9fffea43a0dccd4ebe14a/src/Field/Field.php#L425-L441
train
CableFramework/ServiceContainer
src/Cable/Component/Container.php
Container.singleton
public function singleton($alias, $callback, $share = false) { return $this->add($alias, $callback, $share)->setSingleton(true); }
php
public function singleton($alias, $callback, $share = false) { return $this->add($alias, $callback, $share)->setSingleton(true); }
[ "public", "function", "singleton", "(", "$", "alias", ",", "$", "callback", ",", "$", "share", "=", "false", ")", "{", "return", "$", "this", "->", "add", "(", "$", "alias", ",", "$", "callback", ",", "$", "share", ")", "->", "setSingleton", "(", "...
this method marks your alias as a singleton so it will be resolve only once and reuse everytime @param string $alias the alias name of instance, you might wanna give an interface name @param mixed $callback the callback can be an object, Closure or the name of class @example add('mysql', 'MysqlInterface') @param bool $share if you put true on this argument, this will shared with other container objects @see Container::share() @example add('mysql', 'MysqlInterface', true); @throws ResolverException @return ClassDefinition
[ "this", "method", "marks", "your", "alias", "as", "a", "singleton", "so", "it", "will", "be", "resolve", "only", "once", "and", "reuse", "everytime" ]
0e48ad2e26de9b780d8fe336dd9ac48357285486
https://github.com/CableFramework/ServiceContainer/blob/0e48ad2e26de9b780d8fe336dd9ac48357285486/src/Cable/Component/Container.php#L213-L216
train
CableFramework/ServiceContainer
src/Cable/Component/Container.php
Container.resolve
public function resolve($alias, array $args = []) { // if it is an alias we will solve the orjinal one if (isset($this->aliases[$alias])) { $alias = $this->aliases[$alias]; } $singleton = $this->getBoundManager()->singleton($alias); // determine the alias already resolved before or not. if ($singleton && $this->hasResolvedBefore($alias)) { // we resolved that before, let's reuse it. return $this->getAlreadyResolved($alias); } // we realized we did not add this before if (false === $this->boundManager->has($alias)) { $this->add($alias, $alias); // resolve this service with given args return $this->resolve($alias, $args); } $definition = $this ->boundManager ->findDefinition($alias); // if we add new args, we'll set them into definition if ( ! empty($args)) { $this->getArgumentManager()->setClassArgs( $alias, $args ); } // determine resolved instance is as we expected or not $resolved = $this->checkExpectation( $alias, $this->resolveObject($definition, $alias) ); // we resolved the definition, now we will add into resolvedBond or sharedResolved // and we will reuse they when we want to resolve them $this->saveResolved($alias, $resolved); // we already resolve and saved it. We don't need this definition anymore. // so we will remove it. // this will save memory if ($singleton === true) { $this->removeResolvedFromBound($alias); } return $resolved; }
php
public function resolve($alias, array $args = []) { // if it is an alias we will solve the orjinal one if (isset($this->aliases[$alias])) { $alias = $this->aliases[$alias]; } $singleton = $this->getBoundManager()->singleton($alias); // determine the alias already resolved before or not. if ($singleton && $this->hasResolvedBefore($alias)) { // we resolved that before, let's reuse it. return $this->getAlreadyResolved($alias); } // we realized we did not add this before if (false === $this->boundManager->has($alias)) { $this->add($alias, $alias); // resolve this service with given args return $this->resolve($alias, $args); } $definition = $this ->boundManager ->findDefinition($alias); // if we add new args, we'll set them into definition if ( ! empty($args)) { $this->getArgumentManager()->setClassArgs( $alias, $args ); } // determine resolved instance is as we expected or not $resolved = $this->checkExpectation( $alias, $this->resolveObject($definition, $alias) ); // we resolved the definition, now we will add into resolvedBond or sharedResolved // and we will reuse they when we want to resolve them $this->saveResolved($alias, $resolved); // we already resolve and saved it. We don't need this definition anymore. // so we will remove it. // this will save memory if ($singleton === true) { $this->removeResolvedFromBound($alias); } return $resolved; }
[ "public", "function", "resolve", "(", "$", "alias", ",", "array", "$", "args", "=", "[", "]", ")", "{", "// if it is an alias we will solve the orjinal one", "if", "(", "isset", "(", "$", "this", "->", "aliases", "[", "$", "alias", "]", ")", ")", "{", "$...
resolves the given alias you can give an object, the name of class or the alias name @param string $alias @param array $args @throws ContainerExceptionInterface @return mixed
[ "resolves", "the", "given", "alias" ]
0e48ad2e26de9b780d8fe336dd9ac48357285486
https://github.com/CableFramework/ServiceContainer/blob/0e48ad2e26de9b780d8fe336dd9ac48357285486/src/Cable/Component/Container.php#L383-L440
train
CableFramework/ServiceContainer
src/Cable/Component/Container.php
Container.resolveObject
private function resolveObject($definition, $alias) { if ($definition instanceof \Closure) { return $this->resolveClosure( $alias, $definition ); } try { $class = new \ReflectionClass($definition); } catch (\ReflectionException $exception) { throw new ReflectionException( $exception->getMessage() ); } $this->resolveProviderAnnotations($class); // the given class if is not instantiable throw an exception // that happens when you try resolve an interface or abstract class // without saving an alias on that class before if (false === $class->isInstantiable()) { throw new ReflectionException( sprintf( '%s class in not instantiable, probably an interface or abstract', $class->getName() ) ); } $constructor = $class->getConstructor(); $parameters = []; if (null !== $constructor) { $this->resolveInjectAnnotations($constructor, $alias); $parameters = $this->resolveParameters( $constructor, $this->argumentManager->getClassArgs($alias) ); } return $class->newInstanceArgs($parameters); }
php
private function resolveObject($definition, $alias) { if ($definition instanceof \Closure) { return $this->resolveClosure( $alias, $definition ); } try { $class = new \ReflectionClass($definition); } catch (\ReflectionException $exception) { throw new ReflectionException( $exception->getMessage() ); } $this->resolveProviderAnnotations($class); // the given class if is not instantiable throw an exception // that happens when you try resolve an interface or abstract class // without saving an alias on that class before if (false === $class->isInstantiable()) { throw new ReflectionException( sprintf( '%s class in not instantiable, probably an interface or abstract', $class->getName() ) ); } $constructor = $class->getConstructor(); $parameters = []; if (null !== $constructor) { $this->resolveInjectAnnotations($constructor, $alias); $parameters = $this->resolveParameters( $constructor, $this->argumentManager->getClassArgs($alias) ); } return $class->newInstanceArgs($parameters); }
[ "private", "function", "resolveObject", "(", "$", "definition", ",", "$", "alias", ")", "{", "if", "(", "$", "definition", "instanceof", "\\", "Closure", ")", "{", "return", "$", "this", "->", "resolveClosure", "(", "$", "alias", ",", "$", "definition", ...
resolves the instance @param object $definition @param string $alias @throws ContainerExceptionInterface @throws ContainerNotFoundException @throws ReflectionException @return mixed
[ "resolves", "the", "instance" ]
0e48ad2e26de9b780d8fe336dd9ac48357285486
https://github.com/CableFramework/ServiceContainer/blob/0e48ad2e26de9b780d8fe336dd9ac48357285486/src/Cable/Component/Container.php#L452-L500
train
dazarobbo/Cola
src/Functions/PHPArray.php
PHPArray.each
public static function each(array $arr, \Closure $action){ foreach($arr as $k => $v){ $action($v, $k); } }
php
public static function each(array $arr, \Closure $action){ foreach($arr as $k => $v){ $action($v, $k); } }
[ "public", "static", "function", "each", "(", "array", "$", "arr", ",", "\\", "Closure", "$", "action", ")", "{", "foreach", "(", "$", "arr", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "action", "(", "$", "v", ",", "$", "k", ")", ";", "}",...
Performs an action for each element in the array @param array $arr @param \Closure $action Function with two optional parameters: $v value, $k key
[ "Performs", "an", "action", "for", "each", "element", "in", "the", "array" ]
b101b73ebeb8a571345a303cbc75168f60d0e64f
https://github.com/dazarobbo/Cola/blob/b101b73ebeb8a571345a303cbc75168f60d0e64f/src/Functions/PHPArray.php#L20-L24
train
dazarobbo/Cola
src/Functions/PHPArray.php
PHPArray.filter
public static function filter(array $arr, \Closure $predicate){ $ret = array(); foreach($arr as $k => $v){ if($predicate($v, $k)){ $ret[$k] = $v; } } return $ret; }
php
public static function filter(array $arr, \Closure $predicate){ $ret = array(); foreach($arr as $k => $v){ if($predicate($v, $k)){ $ret[$k] = $v; } } return $ret; }
[ "public", "static", "function", "filter", "(", "array", "$", "arr", ",", "\\", "Closure", "$", "predicate", ")", "{", "$", "ret", "=", "array", "(", ")", ";", "foreach", "(", "$", "arr", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$",...
Traverses an array and generates a new array with the returned values which pass the predicate function @param array $arr @param \Closure $predicate @return array
[ "Traverses", "an", "array", "and", "generates", "a", "new", "array", "with", "the", "returned", "values" ]
b101b73ebeb8a571345a303cbc75168f60d0e64f
https://github.com/dazarobbo/Cola/blob/b101b73ebeb8a571345a303cbc75168f60d0e64f/src/Functions/PHPArray.php#L50-L62
train
dazarobbo/Cola
src/Functions/PHPArray.php
PHPArray.findKey
public static function findKey(array $arr, \Closure $predicate){ foreach($arr as $k => $v){ if($predicate($v, $k)){ return $k; } } return null; }
php
public static function findKey(array $arr, \Closure $predicate){ foreach($arr as $k => $v){ if($predicate($v, $k)){ return $k; } } return null; }
[ "public", "static", "function", "findKey", "(", "array", "$", "arr", ",", "\\", "Closure", "$", "predicate", ")", "{", "foreach", "(", "$", "arr", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "predicate", "(", "$", "v", ",", "$", "...
Returns the key for the element which passes the given predicate function @param array $arr @param \Closure $predicate @return mixed|null null is returned if no match was found
[ "Returns", "the", "key", "for", "the", "element", "which", "passes", "the", "given", "predicate", "function" ]
b101b73ebeb8a571345a303cbc75168f60d0e64f
https://github.com/dazarobbo/Cola/blob/b101b73ebeb8a571345a303cbc75168f60d0e64f/src/Functions/PHPArray.php#L82-L89
train
dazarobbo/Cola
src/Functions/PHPArray.php
PHPArray.keysExist
public static function keysExist(array $arr /*, $key1, $key2, etc...*/){ for($i = 1, $l = \func_num_args() - 1; $i <= $l; ++$i){ if(!\array_key_exists(\func_get_arg($i), $arr)){ return false; } } return true; }
php
public static function keysExist(array $arr /*, $key1, $key2, etc...*/){ for($i = 1, $l = \func_num_args() - 1; $i <= $l; ++$i){ if(!\array_key_exists(\func_get_arg($i), $arr)){ return false; } } return true; }
[ "public", "static", "function", "keysExist", "(", "array", "$", "arr", "/*, $key1, $key2, etc...*/", ")", "{", "for", "(", "$", "i", "=", "1", ",", "$", "l", "=", "\\", "func_num_args", "(", ")", "-", "1", ";", "$", "i", "<=", "$", "l", ";", "++", ...
Checks whether a given set of keys exist in an array @param array $arr The array to search @return bool true if all keys exist, otherwise false
[ "Checks", "whether", "a", "given", "set", "of", "keys", "exist", "in", "an", "array" ]
b101b73ebeb8a571345a303cbc75168f60d0e64f
https://github.com/dazarobbo/Cola/blob/b101b73ebeb8a571345a303cbc75168f60d0e64f/src/Functions/PHPArray.php#L112-L122
train
dazarobbo/Cola
src/Functions/PHPArray.php
PHPArray.map
public static function map(array $arr, \Closure $callback){ $ret = array(); foreach($arr as $k => $v){ $ret[$k] = $callback($v, $k); } return $ret; }
php
public static function map(array $arr, \Closure $callback){ $ret = array(); foreach($arr as $k => $v){ $ret[$k] = $callback($v, $k); } return $ret; }
[ "public", "static", "function", "map", "(", "array", "$", "arr", ",", "\\", "Closure", "$", "callback", ")", "{", "$", "ret", "=", "array", "(", ")", ";", "foreach", "(", "$", "arr", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "ret", "[", ...
Traverses an array and generates a new array with the returned values which a returned from the callback function @param array $arr @param \Closure $callback @return array
[ "Traverses", "an", "array", "and", "generates", "a", "new", "array", "with", "the", "returned", "values", "which", "a", "returned", "from", "the", "callback", "function" ]
b101b73ebeb8a571345a303cbc75168f60d0e64f
https://github.com/dazarobbo/Cola/blob/b101b73ebeb8a571345a303cbc75168f60d0e64f/src/Functions/PHPArray.php#L144-L154
train
dazarobbo/Cola
src/Functions/PHPArray.php
PHPArray.single
public static function single(array $arr, \Closure $predicate){ foreach($arr as $k => $v){ if($predicate($v, $k)){ return $v; } } return null; }
php
public static function single(array $arr, \Closure $predicate){ foreach($arr as $k => $v){ if($predicate($v, $k)){ return $v; } } return null; }
[ "public", "static", "function", "single", "(", "array", "$", "arr", ",", "\\", "Closure", "$", "predicate", ")", "{", "foreach", "(", "$", "arr", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "predicate", "(", "$", "v", ",", "$", "k...
Returns the value of the first matching predicate @param array $arr @param \Closure $predicate @return mixed|null null is returned if no match was found
[ "Returns", "the", "value", "of", "the", "first", "matching", "predicate" ]
b101b73ebeb8a571345a303cbc75168f60d0e64f
https://github.com/dazarobbo/Cola/blob/b101b73ebeb8a571345a303cbc75168f60d0e64f/src/Functions/PHPArray.php#L163-L173
train
dazarobbo/Cola
src/Functions/PHPArray.php
PHPArray.some
public static function some(array $arr, \Closure $predicate){ foreach($arr as $k => $v){ if($predicate($v, $k)){ return true; } } return false; }
php
public static function some(array $arr, \Closure $predicate){ foreach($arr as $k => $v){ if($predicate($v, $k)){ return true; } } return false; }
[ "public", "static", "function", "some", "(", "array", "$", "arr", ",", "\\", "Closure", "$", "predicate", ")", "{", "foreach", "(", "$", "arr", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "predicate", "(", "$", "v", ",", "$", "k",...
Checks if any element passes a predicate function @param array $arr @param \Closure $predicate @return bool
[ "Checks", "if", "any", "element", "passes", "a", "predicate", "function" ]
b101b73ebeb8a571345a303cbc75168f60d0e64f
https://github.com/dazarobbo/Cola/blob/b101b73ebeb8a571345a303cbc75168f60d0e64f/src/Functions/PHPArray.php#L182-L192
train
SocietyCMS/Modules
Manager/PackageInformation.php
PackageInformation.getPackageInfo
public function getPackageInfo($packageName) { $composerLock = json_decode($this->finder->get('composer.lock')); foreach ($composerLock->packages as $package) { if ($package->name == $packageName) { return $package; } } }
php
public function getPackageInfo($packageName) { $composerLock = json_decode($this->finder->get('composer.lock')); foreach ($composerLock->packages as $package) { if ($package->name == $packageName) { return $package; } } }
[ "public", "function", "getPackageInfo", "(", "$", "packageName", ")", "{", "$", "composerLock", "=", "json_decode", "(", "$", "this", "->", "finder", "->", "get", "(", "'composer.lock'", ")", ")", ";", "foreach", "(", "$", "composerLock", "->", "packages", ...
Get the exact installed version for the specified package. @param string $packageName @return string mixed
[ "Get", "the", "exact", "installed", "version", "for", "the", "specified", "package", "." ]
bfb8d29fa47bd61787d16dbb1d14e144eb902ec1
https://github.com/SocietyCMS/Modules/blob/bfb8d29fa47bd61787d16dbb1d14e144eb902ec1/Manager/PackageInformation.php#L26-L34
train
sebardo/ecommerce
EcommerceBundle/Entity/Addressable.php
Addressable.getAddressInfo
public function getAddressInfo() { $address = new Address(); $address->setAddress($this->getAddress()); $address->setPostalCode($this->getPostalCode()); $address->setCity($this->getCity()); if(!is_null($this->getState()))$address->setState($this->getState()); $address->setCountry($this->getCountry()); return $address; }
php
public function getAddressInfo() { $address = new Address(); $address->setAddress($this->getAddress()); $address->setPostalCode($this->getPostalCode()); $address->setCity($this->getCity()); if(!is_null($this->getState()))$address->setState($this->getState()); $address->setCountry($this->getCountry()); return $address; }
[ "public", "function", "getAddressInfo", "(", ")", "{", "$", "address", "=", "new", "Address", "(", ")", ";", "$", "address", "->", "setAddress", "(", "$", "this", "->", "getAddress", "(", ")", ")", ";", "$", "address", "->", "setPostalCode", "(", "$", ...
Get address information @return Address
[ "Get", "address", "information" ]
3e17545e69993f10a1df17f9887810c7378fc7f9
https://github.com/sebardo/ecommerce/blob/3e17545e69993f10a1df17f9887810c7378fc7f9/EcommerceBundle/Entity/Addressable.php#L126-L137
train
koenreiniers/http-client
src/Client.php
HttpClient.send
public function send(RequestInterface $request) { /** @var RequestEvent $event */ $event = new RequestEvent($request); $event = $this->eventDispatcher->dispatch(ClientEvents::REQUEST, $event); $request = $event->getRequest(); $response = $this->httpClient->send($request); /** @var ResponseEvent $event */ $event = new ResponseEvent($response); $event = $this->eventDispatcher->dispatch(ClientEvents::RESPONSE, $event); return $event->getResponse(); }
php
public function send(RequestInterface $request) { /** @var RequestEvent $event */ $event = new RequestEvent($request); $event = $this->eventDispatcher->dispatch(ClientEvents::REQUEST, $event); $request = $event->getRequest(); $response = $this->httpClient->send($request); /** @var ResponseEvent $event */ $event = new ResponseEvent($response); $event = $this->eventDispatcher->dispatch(ClientEvents::RESPONSE, $event); return $event->getResponse(); }
[ "public", "function", "send", "(", "RequestInterface", "$", "request", ")", "{", "/** @var RequestEvent $event */", "$", "event", "=", "new", "RequestEvent", "(", "$", "request", ")", ";", "$", "event", "=", "$", "this", "->", "eventDispatcher", "->", "dispatc...
Sends a psr-7 request, while dispatching request + response events @param RequestInterface $request @return ResponseInterface
[ "Sends", "a", "psr", "-", "7", "request", "while", "dispatching", "request", "+", "response", "events" ]
dd5b5f9bc6569bcfb567a73cbecabae6bf864cc3
https://github.com/koenreiniers/http-client/blob/dd5b5f9bc6569bcfb567a73cbecabae6bf864cc3/src/Client.php#L50-L65
train