repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
phPoirot/Stream
Streamable.php
Streamable._assertStreamAlive
protected function _assertStreamAlive() { if (!$this->resource()->isAlive() || ( $this->resource()->meta() && $this->resource()->meta()->isTimedOut() ) ) { throw new \Exception('Stream is not alive it can be closed or timeout.'); } }
php
protected function _assertStreamAlive() { if (!$this->resource()->isAlive() || ( $this->resource()->meta() && $this->resource()->meta()->isTimedOut() ) ) { throw new \Exception('Stream is not alive it can be closed or timeout.'); } }
...
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L457-L467
hal-platform/hal-core
src/Repository/System/VersionControlProviderRepository.php
VersionControlProviderRepository.getPagedResults
public function getPagedResults($limit = 50, $page = 0) { $dql = sprintf(self::DQL_GET_VCSS, VersionControlProvider::class); return $this->getPaginator($dql, $limit, $page); }
php
public function getPagedResults($limit = 50, $page = 0) { $dql = sprintf(self::DQL_GET_VCSS, VersionControlProvider::class); return $this->getPaginator($dql, $limit, $page); }
Get all VCSs, paged. @param int $limit @param int $page @return Paginator
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/System/VersionControlProviderRepository.php#L60-L65
iron-bound-designs/wp-notifications
src/Template/Listener.php
Listener.get_callback_reflection
public function get_callback_reflection() { if ( is_array( $this->callback ) ) { return new \ReflectionMethod( $this->callback[0], $this->callback[1] ); } else { return new \ReflectionFunction( $this->callback ); } }
php
public function get_callback_reflection() { if ( is_array( $this->callback ) ) { return new \ReflectionMethod( $this->callback[0], $this->callback[1] ); } else { return new \ReflectionFunction( $this->callback ); } }
Get a reflection object for the callback function. @since 1.0 @return \ReflectionFunctionAbstract
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Template/Listener.php#L50-L56
issei-m/spike-php
src/Model/Factory/RefundFactory.php
RefundFactory.create
public function create(array $data) { $refund = new Refund(); $refund ->setCreated($this->dateTimeUtil->createDateTimeByUnixTime($data['created'])) ->setAmount(new Money(floatval($data['amount']), $data['currency'])) ; return $refund; }
php
public function create(array $data) { $refund = new Refund(); $refund ->setCreated($this->dateTimeUtil->createDateTimeByUnixTime($data['created'])) ->setAmount(new Money(floatval($data['amount']), $data['currency'])) ; return $refund; }
{@inheritdoc}
https://github.com/issei-m/spike-php/blob/9205b5047a1132bcdca6731feac02fe3d5dc1023/src/Model/Factory/RefundFactory.php#L28-L37
WolfMicrosystems/ldap
src/WMS/Library/Ldap/Repository/AccountRepository.php
AccountRepository.findAccountsForGroup
public function findAccountsForGroup(Entity\GroupNode $groupNode) { if ($this->getConfiguration()->getMembershipUseAttributeFromGroup() === true) { return $this->findAccountsForGroupUsingGroupAttribute($groupNode); } elseif ($this->getConfiguration()->getMembershipUseAttributeFromUser() === true) { return $this->findAccountsForGroupUsingAccountAttribute($groupNode); } return new Collection\AccountNodeCollection(new Collection\DnIterator($this->connection, array())); }
php
public function findAccountsForGroup(Entity\GroupNode $groupNode) { if ($this->getConfiguration()->getMembershipUseAttributeFromGroup() === true) { return $this->findAccountsForGroupUsingGroupAttribute($groupNode); } elseif ($this->getConfiguration()->getMembershipUseAttributeFromUser() === true) { return $this->findAccountsForGroupUsingAccountAttribute($groupNode); } return new Collection\AccountNodeCollection(new Collection\DnIterator($this->connection, array())); }
@param \WMS\Library\Ldap\Entity\GroupNode $groupNode @return Collection\AccountNodeCollection
https://github.com/WolfMicrosystems/ldap/blob/872bbdc6127a41f0c51f2aa73425b8063a5c8148/src/WMS/Library/Ldap/Repository/AccountRepository.php#L27-L36
WolfMicrosystems/ldap
src/WMS/Library/Ldap/Repository/AccountRepository.php
AccountRepository.findByAccountName
public function findByAccountName($accountName) { $username = $this->connection->getCanonicalAccountName($accountName, Enum\CanonicalAccountNameForm::USERNAME); return $this->searchForOneNode( $this->buildFilter( new Filter\StringFilter($this->connection->getConfiguration()->getAccountUsernameAttribute() . '=' . Filter\AbstractFilter::escapeValue($username)) ) ); }
php
public function findByAccountName($accountName) { $username = $this->connection->getCanonicalAccountName($accountName, Enum\CanonicalAccountNameForm::USERNAME); return $this->searchForOneNode( $this->buildFilter( new Filter\StringFilter($this->connection->getConfiguration()->getAccountUsernameAttribute() . '=' . Filter\AbstractFilter::escapeValue($username)) ) ); }
@param $accountName @return Entity\AccountNode|null
https://github.com/WolfMicrosystems/ldap/blob/872bbdc6127a41f0c51f2aa73425b8063a5c8148/src/WMS/Library/Ldap/Repository/AccountRepository.php#L76-L85
WolfMicrosystems/ldap
src/WMS/Library/Ldap/Repository/AccountRepository.php
AccountRepository.getAccountPictureBlob
public function getAccountPictureBlob($accountName) { $username = $this->connection->getCanonicalAccountName($accountName, Enum\CanonicalAccountNameForm::USERNAME); /** @var Collection\DisconnectedZendLdapNodeCollection $results */ $results = $this->connection->search( $this->buildFilter( new Filter\StringFilter($this->connection->getConfiguration()->getAccountUsernameAttribute() . '=' . Filter\AbstractFilter::escapeValue($username)) ), $this->getSearchBaseDn(), Ldap::SEARCH_SCOPE_SUB, array($this->getConfiguration()->getAccountPictureAttribute()), null, '\WMS\Library\Ldap\Collection\DisconnectedZendLdapNodeCollection', 1 ); if ($results->count() === 0) { return null; } return $results->getFirst()->getAttribute($this->getConfiguration()->getAccountPictureAttribute(), 0); }
php
public function getAccountPictureBlob($accountName) { $username = $this->connection->getCanonicalAccountName($accountName, Enum\CanonicalAccountNameForm::USERNAME); /** @var Collection\DisconnectedZendLdapNodeCollection $results */ $results = $this->connection->search( $this->buildFilter( new Filter\StringFilter($this->connection->getConfiguration()->getAccountUsernameAttribute() . '=' . Filter\AbstractFilter::escapeValue($username)) ), $this->getSearchBaseDn(), Ldap::SEARCH_SCOPE_SUB, array($this->getConfiguration()->getAccountPictureAttribute()), null, '\WMS\Library\Ldap\Collection\DisconnectedZendLdapNodeCollection', 1 ); if ($results->count() === 0) { return null; } return $results->getFirst()->getAttribute($this->getConfiguration()->getAccountPictureAttribute(), 0); }
@param $accountName @return string|null
https://github.com/WolfMicrosystems/ldap/blob/872bbdc6127a41f0c51f2aa73425b8063a5c8148/src/WMS/Library/Ldap/Repository/AccountRepository.php#L92-L114
WolfMicrosystems/ldap
src/WMS/Library/Ldap/Repository/AccountRepository.php
AccountRepository.findAccountsForGroupUsingAccountAttribute
protected function findAccountsForGroupUsingAccountAttribute(Entity\GroupNode $group) { $findValue = $group->getDn(); switch ($this->getConfiguration()->getAccountMembershipAttribute()) { case Enum\AccountMembershipMappingType::NAME: $findValue = $group->getName(); break; } return $this->searchNodes( $this->buildFilter( new Filter\StringFilter($this->getConfiguration()->getAccountMembershipAttribute() . '=' . Filter\AbstractFilter::escapeValue($findValue)) ) ); }
php
protected function findAccountsForGroupUsingAccountAttribute(Entity\GroupNode $group) { $findValue = $group->getDn(); switch ($this->getConfiguration()->getAccountMembershipAttribute()) { case Enum\AccountMembershipMappingType::NAME: $findValue = $group->getName(); break; } return $this->searchNodes( $this->buildFilter( new Filter\StringFilter($this->getConfiguration()->getAccountMembershipAttribute() . '=' . Filter\AbstractFilter::escapeValue($findValue)) ) ); }
@param Entity\GroupNode $group @return Collection\AccountNodeCollection
https://github.com/WolfMicrosystems/ldap/blob/872bbdc6127a41f0c51f2aa73425b8063a5c8148/src/WMS/Library/Ldap/Repository/AccountRepository.php#L121-L136
WolfMicrosystems/ldap
src/WMS/Library/Ldap/Repository/AccountRepository.php
AccountRepository.findAccountsForGroupUsingGroupAttribute
protected function findAccountsForGroupUsingGroupAttribute(Entity\GroupNode $group) { $groupAttrValues = $group->getRawLdapNode()->getAttribute($this->getConfiguration()->getGroupMembersAttribute()); $filterProperty = ''; switch ($this->getConfiguration()->getGroupMembersAttributeMappingType()) { case Enum\GroupMembersMappingType::DN: return new Collection\GroupNodeCollection(new Collection\DnIterator($this->connection, array($groupAttrValues))); case Enum\GroupMembersMappingType::USERNAME: $filterProperty = $this->getConfiguration()->getAccountUsernameAttribute(); break; case Enum\GroupMembersMappingType::UNIQUE_ID: $filterProperty = $this->getConfiguration()->getAccountUniqueIdAttribute(); break; } $filters = array(); foreach ($groupAttrValues as $groupAttrValue) { $filters[] = new Filter\StringFilter($filterProperty . '=' . Filter\AbstractFilter::escapeValue($groupAttrValue)); } return $this->searchNodes( $this->buildFilter( new Filter\OrFilter($filters) ) ); }
php
protected function findAccountsForGroupUsingGroupAttribute(Entity\GroupNode $group) { $groupAttrValues = $group->getRawLdapNode()->getAttribute($this->getConfiguration()->getGroupMembersAttribute()); $filterProperty = ''; switch ($this->getConfiguration()->getGroupMembersAttributeMappingType()) { case Enum\GroupMembersMappingType::DN: return new Collection\GroupNodeCollection(new Collection\DnIterator($this->connection, array($groupAttrValues))); case Enum\GroupMembersMappingType::USERNAME: $filterProperty = $this->getConfiguration()->getAccountUsernameAttribute(); break; case Enum\GroupMembersMappingType::UNIQUE_ID: $filterProperty = $this->getConfiguration()->getAccountUniqueIdAttribute(); break; } $filters = array(); foreach ($groupAttrValues as $groupAttrValue) { $filters[] = new Filter\StringFilter($filterProperty . '=' . Filter\AbstractFilter::escapeValue($groupAttrValue)); } return $this->searchNodes( $this->buildFilter( new Filter\OrFilter($filters) ) ); }
@param Entity\GroupNode $group @return Collection\AccountNodeCollection
https://github.com/WolfMicrosystems/ldap/blob/872bbdc6127a41f0c51f2aa73425b8063a5c8148/src/WMS/Library/Ldap/Repository/AccountRepository.php#L143-L172
etd-framework/form
src/Field/BooleanField.php
BooleanField.getInput
protected function getInput() { $class = $this->element['class'] ? ' ' . (string)$this->element['class'] : ''; $trueLabel = $this->element['trueLabel'] ? (string)$this->element['trueLabel'] : 'APP_GLOBAL_YES'; $falseLabel = $this->element['falseLabel'] ? (string)$this->element['falseLabel'] : 'APP_GLOBAL_NO'; $buttonClass = $this->element['buttonClass'] ? ' ' . (string)$this->element['buttonClass'] : ''; $readonly = isset($this->element['readonly']) ? (bool)$this->element['readonly'] : false; $checked1 = ''; $active1 = ''; $checked0 = ''; $active0 = ''; if (isset($this->value)) { $value = (bool)$this->value; $checked1 = $value ? ' checked="checked"' : ''; $active1 = $value ? ' active' : ''; $checked0 = !$value ? ' checked="checked"' : ''; $active0 = !$value ? ' active' : ''; } $html = ""; if ($readonly) { $html .= '<input type="hidden" name="' . $this->name . '" value="' . $this->value . '">'; if (empty($checked0)) { $html .= $this->getText()->translate($trueLabel); } else { $html .= $this->getText()->translate($falseLabel); } } else { $html .= '<div class="btn-group' . $class . '" data-toggle="buttons"> <label class="btn' . $buttonClass . $active1 . '"> <input type="radio" name="' . $this->name . '" id="' . $this->id . '1"' . $checked1 . ' value="1"> ' . $this->getText()->translate($trueLabel) . ' </label> <label class="btn' . $buttonClass . $active0 . '"> <input type="radio" name="' . $this->name . '" id="' . $this->id . '0"' . $checked0 . ' value="0"> ' . $this->getText()->translate($falseLabel) . ' </label> </div>'; } return $html; }
php
protected function getInput() { $class = $this->element['class'] ? ' ' . (string)$this->element['class'] : ''; $trueLabel = $this->element['trueLabel'] ? (string)$this->element['trueLabel'] : 'APP_GLOBAL_YES'; $falseLabel = $this->element['falseLabel'] ? (string)$this->element['falseLabel'] : 'APP_GLOBAL_NO'; $buttonClass = $this->element['buttonClass'] ? ' ' . (string)$this->element['buttonClass'] : ''; $readonly = isset($this->element['readonly']) ? (bool)$this->element['readonly'] : false; $checked1 = ''; $active1 = ''; $checked0 = ''; $active0 = ''; if (isset($this->value)) { $value = (bool)$this->value; $checked1 = $value ? ' checked="checked"' : ''; $active1 = $value ? ' active' : ''; $checked0 = !$value ? ' checked="checked"' : ''; $active0 = !$value ? ' active' : ''; } $html = ""; if ($readonly) { $html .= '<input type="hidden" name="' . $this->name . '" value="' . $this->value . '">'; if (empty($checked0)) { $html .= $this->getText()->translate($trueLabel); } else { $html .= $this->getText()->translate($falseLabel); } } else { $html .= '<div class="btn-group' . $class . '" data-toggle="buttons"> <label class="btn' . $buttonClass . $active1 . '"> <input type="radio" name="' . $this->name . '" id="' . $this->id . '1"' . $checked1 . ' value="1"> ' . $this->getText()->translate($trueLabel) . ' </label> <label class="btn' . $buttonClass . $active0 . '"> <input type="radio" name="' . $this->name . '" id="' . $this->id . '0"' . $checked0 . ' value="0"> ' . $this->getText()->translate($falseLabel) . ' </label> </div>'; } return $html; }
Method to get the radio button field input markup. @return string The field input markup. @since 1.0
https://github.com/etd-framework/form/blob/65f00f3372fced5948d945ce802a19c0e7abe6e9/src/Field/BooleanField.php#L30-L80
liufee/cms-core
backend/widgets/ueditor/UeditorAction.php
UeditorAction.run
public function run() { $action = strtolower(Yii::$app->request->get('action', 'config')); $actions = [ 'uploadimage' => 'uploadImage', 'uploadscrawl' => 'uploadScrawl', 'uploadvideo' => 'uploadVideo', 'uploadfile' => 'uploadFile', 'listimage' => 'listImage', 'listfile' => 'listFile', 'catchimage' => 'catchImage', 'config' => 'config', 'listinfo' => 'ListInfo' ]; if (isset($actions[$action])) { yii::$app->getResponse()->format = yii\web\Response::FORMAT_JSON; return call_user_func_array([$this, 'action' . $actions[$action]], []); } else { return $this->show(['state' => 'Unknown action.']); } }
php
public function run() { $action = strtolower(Yii::$app->request->get('action', 'config')); $actions = [ 'uploadimage' => 'uploadImage', 'uploadscrawl' => 'uploadScrawl', 'uploadvideo' => 'uploadVideo', 'uploadfile' => 'uploadFile', 'listimage' => 'listImage', 'listfile' => 'listFile', 'catchimage' => 'catchImage', 'config' => 'config', 'listinfo' => 'ListInfo' ]; if (isset($actions[$action])) { yii::$app->getResponse()->format = yii\web\Response::FORMAT_JSON; return call_user_func_array([$this, 'action' . $actions[$action]], []); } else { return $this->show(['state' => 'Unknown action.']); } }
统一后台入口
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/UeditorAction.php#L125-L146
liufee/cms-core
backend/widgets/ueditor/UeditorAction.php
UeditorAction.imageHandle
protected function imageHandle($file) { if (substr($file, 0, 1) != '/') { $file = '/' . $file; } //先处理缩略图 if ($this->thumbnail && ! empty($this->thumbnail['height']) && ! empty($this->thumbnail['width'])) { $file = pathinfo($file); $file = $file['dirname'] . '/' . $file['filename'] . '.thumbnail.' . $file['extension']; Image::thumbnail($this->uploadPath . $file, intval($this->thumbnail['width']), intval($this->thumbnail['height'])) ->save($this->uploadPath . $file); } //再处理缩放,默认不缩放 //...缩放效果非常差劲-,- if (isset($this->zoom['height']) && isset($this->zoom['width'])) { $size = $this->getSize($this->uploadPath . $file); if ($size && $size[0] > 0 && $size[1] > 0) { $ratio = min([$this->zoom['height'] / $size[0], $this->zoom['width'] / $size[1], 1]); Image::thumbnail($this->uploadPath . $file, ceil($size[0] * $ratio), ceil($size[1] * $ratio)) ->save($this->uploadPath . $file); } } //最后生成水印 if (isset($this->watermark['path']) && file_exists($this->watermark['path'])) { if (! isset($this->watermark['position']) or $this->watermark['position'] > 9 or $this->watermark['position'] < 0 or ! is_numeric($this->watermark['position'])) { $this->watermark['position'] = 9; } $size = $this->getSize($this->uploadPath . $file); $waterSize = $this->getSize($this->watermark['path']); if ($size[0] > $waterSize[0] and $size[1] > $waterSize[1]) { $halfX = $size[0] / 2; $halfY = $size[1] / 2; $halfWaterX = $waterSize[0] / 2; $halfWaterY = $waterSize[1] / 2; switch (intval($this->watermark['position'])) { case 1: $x = 0; $y = 0; break; case 2: $x = $halfX - $halfWaterX; $y = 0; break; case 3: $x = $size[0] - $waterSize[0]; $y = 0; break; case 4: $x = 0; $y = $halfY - $halfWaterY; break; case 5: $x = $halfX - $halfWaterX; $y = $halfY - $halfWaterY; break; case 6: $x = $size[0] - $waterSize[0]; $y = $halfY - $halfWaterY; break; case 7: $x = 0; $y = $size[1] - $waterSize[1]; break; case 8: $x = $halfX - $halfWaterX; $y = $size[1] - $waterSize[1]; break; case 9: default: $x = $size[0] - $waterSize[0]; $y = $size[1] - $waterSize[1]; } Image::watermark($this->uploadPath . $file, $this->watermark['path'], [$x, $y]) ->save($this->uploadPath . $file); } } return $file; }
php
protected function imageHandle($file) { if (substr($file, 0, 1) != '/') { $file = '/' . $file; } //先处理缩略图 if ($this->thumbnail && ! empty($this->thumbnail['height']) && ! empty($this->thumbnail['width'])) { $file = pathinfo($file); $file = $file['dirname'] . '/' . $file['filename'] . '.thumbnail.' . $file['extension']; Image::thumbnail($this->uploadPath . $file, intval($this->thumbnail['width']), intval($this->thumbnail['height'])) ->save($this->uploadPath . $file); } //再处理缩放,默认不缩放 //...缩放效果非常差劲-,- if (isset($this->zoom['height']) && isset($this->zoom['width'])) { $size = $this->getSize($this->uploadPath . $file); if ($size && $size[0] > 0 && $size[1] > 0) { $ratio = min([$this->zoom['height'] / $size[0], $this->zoom['width'] / $size[1], 1]); Image::thumbnail($this->uploadPath . $file, ceil($size[0] * $ratio), ceil($size[1] * $ratio)) ->save($this->uploadPath . $file); } } //最后生成水印 if (isset($this->watermark['path']) && file_exists($this->watermark['path'])) { if (! isset($this->watermark['position']) or $this->watermark['position'] > 9 or $this->watermark['position'] < 0 or ! is_numeric($this->watermark['position'])) { $this->watermark['position'] = 9; } $size = $this->getSize($this->uploadPath . $file); $waterSize = $this->getSize($this->watermark['path']); if ($size[0] > $waterSize[0] and $size[1] > $waterSize[1]) { $halfX = $size[0] / 2; $halfY = $size[1] / 2; $halfWaterX = $waterSize[0] / 2; $halfWaterY = $waterSize[1] / 2; switch (intval($this->watermark['position'])) { case 1: $x = 0; $y = 0; break; case 2: $x = $halfX - $halfWaterX; $y = 0; break; case 3: $x = $size[0] - $waterSize[0]; $y = 0; break; case 4: $x = 0; $y = $halfY - $halfWaterY; break; case 5: $x = $halfX - $halfWaterX; $y = $halfY - $halfWaterY; break; case 6: $x = $size[0] - $waterSize[0]; $y = $halfY - $halfWaterY; break; case 7: $x = 0; $y = $size[1] - $waterSize[1]; break; case 8: $x = $halfX - $halfWaterX; $y = $size[1] - $waterSize[1]; break; case 9: default: $x = $size[0] - $waterSize[0]; $y = $size[1] - $waterSize[1]; } Image::watermark($this->uploadPath . $file, $this->watermark['path'], [$x, $y]) ->save($this->uploadPath . $file); } } return $file; }
自动处理图片 @param $file @return mixed|string
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/UeditorAction.php#L318-L398
liufee/cms-core
backend/widgets/ueditor/UeditorAction.php
UeditorAction.getSize
protected function getSize($file) { if (! file_exists($file)) { return []; } $info = pathinfo($file); $image = null; switch (strtolower($info['extension'])) { case 'gif': $image = imagecreatefromgif($file); break; case 'jpg': case 'jpeg': $image = imagecreatefromjpeg($file); break; case 'png': $image = imagecreatefrompng($file); break; default: break; } if ($image == null) { return []; } else { return [imagesx($image), imagesy($image)]; } }
php
protected function getSize($file) { if (! file_exists($file)) { return []; } $info = pathinfo($file); $image = null; switch (strtolower($info['extension'])) { case 'gif': $image = imagecreatefromgif($file); break; case 'jpg': case 'jpeg': $image = imagecreatefromjpeg($file); break; case 'png': $image = imagecreatefrompng($file); break; default: break; } if ($image == null) { return []; } else { return [imagesx($image), imagesy($image)]; } }
获取图片的大小 主要用于获取图片大小并 @param $file @return array
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/UeditorAction.php#L407-L434
liufee/cms-core
backend/widgets/ueditor/UeditorAction.php
UeditorAction.manage
protected function manage($allowFiles, $listSize, $path) { $allowFiles = substr(str_replace('.', '|', join('', $allowFiles)), 1); /* 获取参数 */ $size = isset($_GET['size']) ? $_GET['size'] : $listSize; $start = isset($_GET['start']) ? $_GET['start'] : 0; $end = $start + $size; /* 获取文件列表 */ $path = yii::getAlias('@ueditor') . (substr($path, 0, 1) == '/' ? '' : '/') . $path; $files = $this->getFiles($path, $allowFiles); if (! count($files)) { $result = [ 'state' => 'no match file', 'list' => [], 'start' => $start, 'total' => count($files), ]; return $result; } /* 获取指定范围的列表 */ $len = count($files); for ($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--) { $list[] = $files[$i]; } /* 返回数据 */ $result = [ 'state' => 'SUCCESS', 'list' => $list, 'start' => $start, 'total' => count($files), ]; return $result; }
php
protected function manage($allowFiles, $listSize, $path) { $allowFiles = substr(str_replace('.', '|', join('', $allowFiles)), 1); /* 获取参数 */ $size = isset($_GET['size']) ? $_GET['size'] : $listSize; $start = isset($_GET['start']) ? $_GET['start'] : 0; $end = $start + $size; /* 获取文件列表 */ $path = yii::getAlias('@ueditor') . (substr($path, 0, 1) == '/' ? '' : '/') . $path; $files = $this->getFiles($path, $allowFiles); if (! count($files)) { $result = [ 'state' => 'no match file', 'list' => [], 'start' => $start, 'total' => count($files), ]; return $result; } /* 获取指定范围的列表 */ $len = count($files); for ($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--) { $list[] = $files[$i]; } /* 返回数据 */ $result = [ 'state' => 'SUCCESS', 'list' => $list, 'start' => $start, 'total' => count($files), ]; return $result; }
文件和图片管理action使用 @param $allowFiles @param $listSize @param $path @return array
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/UeditorAction.php#L444-L477
liufee/cms-core
backend/widgets/ueditor/UeditorAction.php
UeditorAction.getFiles
protected function getFiles($path, $allowFiles, &$files = []) { if (! is_dir($path)) { return null; } if (in_array(basename($path), $this->ignoreDir)) { return null; } if (substr($path, strlen($path) - 1) != '/') { $path .= '/'; } $handle = opendir($path); //baseUrl用于兼容使用alias的二级目录部署方式 $baseUrl = str_replace(yii::getAlias('@frontend/web'), '', yii::getAlias('@ueditor')); while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { $path2 = $path . $file; if (is_dir($path2)) { $this->getFiles($path2, $allowFiles, $files); } else { if ($this->controller->action->id == 'list-image' && $this->thumbnail) { $pat = "/\.thumbnail\.(" . $allowFiles . ")$/i"; } else { $pat = "/\.(" . $allowFiles . ")$/i"; } if (preg_match($pat, $file)) { $files[] = [ 'url' => yii::$app->params['site']['url'] . $baseUrl . substr($path2, strlen(yii::getAlias('@ueditor'))), 'mtime' => filemtime($path2) ]; } } } } return $files; }
php
protected function getFiles($path, $allowFiles, &$files = []) { if (! is_dir($path)) { return null; } if (in_array(basename($path), $this->ignoreDir)) { return null; } if (substr($path, strlen($path) - 1) != '/') { $path .= '/'; } $handle = opendir($path); //baseUrl用于兼容使用alias的二级目录部署方式 $baseUrl = str_replace(yii::getAlias('@frontend/web'), '', yii::getAlias('@ueditor')); while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { $path2 = $path . $file; if (is_dir($path2)) { $this->getFiles($path2, $allowFiles, $files); } else { if ($this->controller->action->id == 'list-image' && $this->thumbnail) { $pat = "/\.thumbnail\.(" . $allowFiles . ")$/i"; } else { $pat = "/\.(" . $allowFiles . ")$/i"; } if (preg_match($pat, $file)) { $files[] = [ 'url' => yii::$app->params['site']['url'] . $baseUrl . substr($path2, strlen(yii::getAlias('@ueditor'))), 'mtime' => filemtime($path2) ]; } } } } return $files; }
遍历获取目录下的指定类型的文件 @param $path @param $allowFiles @param array $files @return array|null
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/widgets/ueditor/UeditorAction.php#L487-L522
spiral/views
src/Engine/Native/NativeView.php
NativeView.render
public function render(array $data = []): string { ob_start(); $__outputLevel__ = ob_get_level(); try { ContainerScope::runScope($this->container, function () use ($data) { extract($data, EXTR_OVERWRITE); // render view in context and output buffer scope, context can be accessed using $this->context require $this->view->getFilename(); }); } catch (\Throwable $e) { while (ob_get_level() >= $__outputLevel__) { ob_end_clean(); } throw new RenderException($e); } finally { //Closing all nested buffers while (ob_get_level() > $__outputLevel__) { ob_end_clean(); } } return ob_get_clean(); }
php
public function render(array $data = []): string { ob_start(); $__outputLevel__ = ob_get_level(); try { ContainerScope::runScope($this->container, function () use ($data) { extract($data, EXTR_OVERWRITE); // render view in context and output buffer scope, context can be accessed using $this->context require $this->view->getFilename(); }); } catch (\Throwable $e) { while (ob_get_level() >= $__outputLevel__) { ob_end_clean(); } throw new RenderException($e); } finally { //Closing all nested buffers while (ob_get_level() > $__outputLevel__) { ob_end_clean(); } } return ob_get_clean(); }
{@inheritdoc}
https://github.com/spiral/views/blob/0e35697204dfffabf71546d20e89f14b50414a9a/src/Engine/Native/NativeView.php#L45-L70
stefanotorresi/MyBase
src/Form/Element/AbstractPrefilledSelect.php
AbstractPrefilledSelect.setOptions
public function setOptions($options) { parent::setOptions($options); if (isset($this->options['inarray_validator_message'])) { $this->setInArrayValidatorMessage($this->options['inarray_validator_message']); } return $this; }
php
public function setOptions($options) { parent::setOptions($options); if (isset($this->options['inarray_validator_message'])) { $this->setInArrayValidatorMessage($this->options['inarray_validator_message']); } return $this; }
{@inheritdoc}
https://github.com/stefanotorresi/MyBase/blob/9ed131a1e36b4b6cbd9989ae27c849f60bba0a03/src/Form/Element/AbstractPrefilledSelect.php#L34-L43
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.cache
public function cache(): void { Cacher::getInstance()->set( $this->getCacheName(), array_replace( array( 'class' => get_class($this), ), $this->getCacheData() ) ); }
php
public function cache(): void { Cacher::getInstance()->set( $this->getCacheName(), array_replace( array( 'class' => get_class($this), ), $this->getCacheData() ) ); }
Cache
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L30-L41
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.getCacheData
protected function getCacheData(): array { $data = array( 'data' => array(), ); foreach (get_declared_classes() as $class) { $reflector = new \ReflectionClass($class); if ($this->isCorrectAbstractItem($reflector) && $this->isCorrectItem($reflector)) $data = $this->pushClassData($data, $reflector); } return $data; }
php
protected function getCacheData(): array { $data = array( 'data' => array(), ); foreach (get_declared_classes() as $class) { $reflector = new \ReflectionClass($class); if ($this->isCorrectAbstractItem($reflector) && $this->isCorrectItem($reflector)) $data = $this->pushClassData($data, $reflector); } return $data; }
Get cache data @return array
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L48-L63
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.pushClassData
protected function pushClassData(array $data, \ReflectionClass $reflector): array { return $this->collectClassData( $reflector->newInstanceWithoutConstructor(), $data, $reflector ); }
php
protected function pushClassData(array $data, \ReflectionClass $reflector): array { return $this->collectClassData( $reflector->newInstanceWithoutConstructor(), $data, $reflector ); }
Push class data @param array $data @param \ReflectionClass $reflector @return array
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L73-L80
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.collectClassData
protected function collectClassData($item, array $data, \ReflectionClass $reflector): array { foreach ($this->getClassVariants($reflector, $item) as $name) { $key = $this->getItemKey($name); if (!array_key_exists($key, $data['data']) || $this->isItemGreedy($data['data'][$key], $reflector, $item)) $data = $this->addClassData($data, $key, $reflector, $item, $name); } return $data; }
php
protected function collectClassData($item, array $data, \ReflectionClass $reflector): array { foreach ($this->getClassVariants($reflector, $item) as $name) { $key = $this->getItemKey($name); if (!array_key_exists($key, $data['data']) || $this->isItemGreedy($data['data'][$key], $reflector, $item)) $data = $this->addClassData($data, $key, $reflector, $item, $name); } return $data; }
Collect class data @param object $item @param array $data @param \ReflectionClass $reflector @return array
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L91-L102
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.addClassData
protected function addClassData(array $data, string $key, \ReflectionClass $reflector, $item, $variant): array { $data['data'][$key] = $this->getClassData($reflector, $item, $variant); return $data; }
php
protected function addClassData(array $data, string $key, \ReflectionClass $reflector, $item, $variant): array { $data['data'][$key] = $this->getClassData($reflector, $item, $variant); return $data; }
Add class data @param array $data @param string $key @param \ReflectionClass $reflector @param object $item @param mixed $variant @return array
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L115-L120
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.isItemGreedy
protected function isItemGreedy(array $info, \ReflectionClass $reflector, $item): bool { $base = new \ReflectionClass($info['class']); if ($reflector->isSubclassOf($base->getName())) return true; if (!$base->isSubclassOf($reflector->getName())) throw new \LogicException('Class ' . var_export($reflector->getName(), true) . ' has no direct relation with class ' . var_export($base->getName(), true) . '. Use @easy-extend-base to create new branch.'); return false; }
php
protected function isItemGreedy(array $info, \ReflectionClass $reflector, $item): bool { $base = new \ReflectionClass($info['class']); if ($reflector->isSubclassOf($base->getName())) return true; if (!$base->isSubclassOf($reflector->getName())) throw new \LogicException('Class ' . var_export($reflector->getName(), true) . ' has no direct relation with class ' . var_export($base->getName(), true) . '. Use @easy-extend-base to create new branch.'); return false; }
Returns true if item is greedy @param array $info @param \ReflectionClass $reflector @param object $item @return bool
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L162-L173
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.getClassBaseNames
protected function getClassBaseNames($item): array { $basenames = array(); $reflector = new \ReflectionClass($item); do { if (!$reflector->isAbstract()) { $docComment = $reflector->getDocComment(); if ($docComment && strpos($docComment, '@easy-extend-base') !== false) { $basenames[] = $reflector->getName(); return $basenames; } $basenames[] = $reflector->getName(); } $parent = $reflector->getParentClass(); if (!$parent) break; $reflector = new \ReflectionClass($parent->getName()); } while (true); return $basenames; }
php
protected function getClassBaseNames($item): array { $basenames = array(); $reflector = new \ReflectionClass($item); do { if (!$reflector->isAbstract()) { $docComment = $reflector->getDocComment(); if ($docComment && strpos($docComment, '@easy-extend-base') !== false) { $basenames[] = $reflector->getName(); return $basenames; } $basenames[] = $reflector->getName(); } $parent = $reflector->getParentClass(); if (!$parent) break; $reflector = new \ReflectionClass($parent->getName()); } while (true); return $basenames; }
Get class base names @param object $item @return array
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L196-L226
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.getClassTraits
protected function getClassTraits(\ReflectionClass $reflector): array { $class = $reflector->getName(); $traits = array(); do { $traits = array_merge(class_uses($class), $traits); } while ($class = get_parent_class($class)); foreach ($traits as $trait) $traits = array_merge(class_uses($trait), $traits); return array_keys(array_unique($traits)); }
php
protected function getClassTraits(\ReflectionClass $reflector): array { $class = $reflector->getName(); $traits = array(); do { $traits = array_merge(class_uses($class), $traits); } while ($class = get_parent_class($class)); foreach ($traits as $trait) $traits = array_merge(class_uses($trait), $traits); return array_keys(array_unique($traits)); }
Get class traits @param \ReflectionClass $reflector @return array
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L269-L285
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.loadCache
protected function loadCache(): array { if ($this->_cache === null) $this->_cache = Cacher::getInstance()->get($this->getCacheName()); return $this->_cache; }
php
protected function loadCache(): array { if ($this->_cache === null) $this->_cache = Cacher::getInstance()->get($this->getCacheName()); return $this->_cache; }
Load cache @return array
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L340-L346
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.getItem
public function getItem($name) { if (func_num_args() > 1) $name = func_get_args(); $info = $this->getItemData($name); $class = $info['class']; return new $class(); }
php
public function getItem($name) { if (func_num_args() > 1) $name = func_get_args(); $info = $this->getItemData($name); $class = $info['class']; return new $class(); }
Get item @param string|array $name @return mixed
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L355-L364
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.getItemData
public function getItemData($name): array { if (func_num_args() > 1) $name = func_get_args(); if (!$this->hasItemData($name)) return $this->getItemDataNotFound($name); return $this->getData()[$this->getItemKey($name)]; }
php
public function getItemData($name): array { if (func_num_args() > 1) $name = func_get_args(); if (!$this->hasItemData($name)) return $this->getItemDataNotFound($name); return $this->getData()[$this->getItemKey($name)]; }
Get item data @param string|array $name @return array
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L383-L392
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.hasItemData
public function hasItemData($name): bool { if (func_num_args() > 1) $name = func_get_args(); return array_key_exists($this->getItemKey($name), $this->getData()); }
php
public function hasItemData($name): bool { if (func_num_args() > 1) $name = func_get_args(); return array_key_exists($this->getItemKey($name), $this->getData()); }
Has item data @param string|array $name @return bool
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L401-L407
apishka/easy-extend
source/RouterAbstract.php
RouterAbstract.getItemKey
public function getItemKey($name): string { if (func_num_args() > 1) $name = func_get_args(); if (is_array($name)) return implode('|', $name); return (string) $name; }
php
public function getItemKey($name): string { if (func_num_args() > 1) $name = func_get_args(); if (is_array($name)) return implode('|', $name); return (string) $name; }
Returns item key @param string|array $name @return string
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/RouterAbstract.php#L416-L425
slickframework/form
src/Input/ValidationAwareMethods.php
ValidationAwareMethods.isValid
public function isValid() { $valid = $this->valid; if ($this->isMultiple()) { $valid = $this->isMultipleValid(); } return $valid; }
php
public function isValid() { $valid = $this->valid; if ($this->isMultiple()) { $valid = $this->isMultipleValid(); } return $valid; }
Check if the value is valid The value should pass through all validators in the validation chain @return boolean True if is valid, false otherwise
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/ValidationAwareMethods.php#L64-L71
slickframework/form
src/Input/ValidationAwareMethods.php
ValidationAwareMethods.isMultipleValid
protected function isMultipleValid() { if (!$this->isRendering()) { return empty($this->invalidInstances); } return ! in_array($this->getInstance(), $this->invalidInstances); }
php
protected function isMultipleValid() { if (!$this->isRendering()) { return empty($this->invalidInstances); } return ! in_array($this->getInstance(), $this->invalidInstances); }
Validates when input is set to be multiple @return bool
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/ValidationAwareMethods.php#L78-L85
slickframework/form
src/Input/ValidationAwareMethods.php
ValidationAwareMethods.validate
public function validate() { $context = array_merge(['input' => $this], $this->context); $values = $this->getValue(); if (!is_array($values)) { $this->valid = $this->getValidationChain() ->validates($this->getValue(), $context); return $this; } $this->validateArray($values, $context); return $this; }
php
public function validate() { $context = array_merge(['input' => $this], $this->context); $values = $this->getValue(); if (!is_array($values)) { $this->valid = $this->getValidationChain() ->validates($this->getValue(), $context); return $this; } $this->validateArray($values, $context); return $this; }
Validates current value so that isValid can retrieve the result of the validation(s) @return self|$this|ValidationAwareInterface
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/ValidationAwareMethods.php#L93-L104
slickframework/form
src/Input/ValidationAwareMethods.php
ValidationAwareMethods.validateArray
protected function validateArray(array $values, $context) { foreach ($values as $key => $value) { $valid = $this->getValidationChain() ->validates($value, $context); if (!$valid) { $this->setInvalid($key); } } }
php
protected function validateArray(array $values, $context) { foreach ($values as $key => $value) { $valid = $this->getValidationChain() ->validates($value, $context); if (!$valid) { $this->setInvalid($key); } } }
Validates input when is set to be multiple @param array $values @param array $context
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/ValidationAwareMethods.php#L112-L121
slickframework/form
src/Input/ValidationAwareMethods.php
ValidationAwareMethods.addValidator
public function addValidator($validator, $message = null) { try { $msg = $message; if (is_array($message)) { $msg = array_shift($message); $this->context = $message; } $validator = StaticValidator::create($validator, $msg); $this->getValidationChain() ->add($validator); if ($validator instanceof NotEmpty) { $this->setRequired(true); } } catch (ValidatorException $caught) { throw new InvalidArgumentException( $caught->getMessage(), 0, $caught ); } return $this; }
php
public function addValidator($validator, $message = null) { try { $msg = $message; if (is_array($message)) { $msg = array_shift($message); $this->context = $message; } $validator = StaticValidator::create($validator, $msg); $this->getValidationChain() ->add($validator); if ($validator instanceof NotEmpty) { $this->setRequired(true); } } catch (ValidatorException $caught) { throw new InvalidArgumentException( $caught->getMessage(), 0, $caught ); } return $this; }
Adds a validator to the validation chain The validator param could be a known validator alias, a FQ ValidatorInterface class name or an object implementing ValidatorInterface. @param string|ValidatorInterface $validator @param string|array $message Error message and possible contexts variables. @return self|$this|ValidationAwareInterface|ElementInterface @throws InvalidArgumentException If the provided validator is an unknown validator alias or not a valid class name or the object passed does not implement the ValidatorInterface interface.
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/ValidationAwareMethods.php#L179-L201
Aquarmini/limx-package
src/Package.php
Package.run
public function run() { if ($this->isConfig()) { $app = $this->config; $res = \limx\func\File::copy($app['root'], $app['files'], $app['dst']); if ($res === false) { $this->error('the files copy failed'); return false; } $vi = empty($app['vi']) ? 'master' : $app['vi']; $zipname = basename($app['dst']) . '_vi.' . $vi . '.' . time() . '.zip'; $res = \limx\func\File::zip(dirname($app['dst']), basename($app['dst']), dirname($app['dst']), $zipname); if ($res === true) { $this->info('package the program success'); } else { $this->error('zip files failed:code=' . $res); } } }
php
public function run() { if ($this->isConfig()) { $app = $this->config; $res = \limx\func\File::copy($app['root'], $app['files'], $app['dst']); if ($res === false) { $this->error('the files copy failed'); return false; } $vi = empty($app['vi']) ? 'master' : $app['vi']; $zipname = basename($app['dst']) . '_vi.' . $vi . '.' . time() . '.zip'; $res = \limx\func\File::zip(dirname($app['dst']), basename($app['dst']), dirname($app['dst']), $zipname); if ($res === true) { $this->info('package the program success'); } else { $this->error('zip files failed:code=' . $res); } } }
[run desc] @desc 打包程序 @author limx
https://github.com/Aquarmini/limx-package/blob/e8a003ca573110d2f4e2944c05496a898bb40d28/src/Package.php#L42-L60
Aquarmini/limx-package
src/Package.php
Package.isConfig
private function isConfig() { if (empty($this->config['root']) || empty($this->config['files']) || empty($this->config['dst']) || empty($this->config['vi']) ) { $this->error('the config is error!'); return false; } return true; }
php
private function isConfig() { if (empty($this->config['root']) || empty($this->config['files']) || empty($this->config['dst']) || empty($this->config['vi']) ) { $this->error('the config is error!'); return false; } return true; }
[isConfig desc] @desc 查看配置是否正确 @author limx
https://github.com/Aquarmini/limx-package/blob/e8a003ca573110d2f4e2944c05496a898bb40d28/src/Package.php#L67-L76
air-php/http
src/Request/Request.php
Request.getRequestData
public function getRequestData($key = null, $default = null) { if (!is_null($key)) { if (isset($this->requestData[$key])) { return $this->requestData[$key]; } else { return $default; } } else { return $this->requestData; } }
php
public function getRequestData($key = null, $default = null) { if (!is_null($key)) { if (isset($this->requestData[$key])) { return $this->requestData[$key]; } else { return $default; } } else { return $this->requestData; } }
@param mixed $key The data key. @param mixed $default The value to return if the key is not found. @return mixed The request data.
https://github.com/air-php/http/blob/213c02e537cea3d949cc8dbb1218c60c070fce8a/src/Request/Request.php#L135-L146
air-php/http
src/Request/Request.php
Request.getReferer
public function getReferer() { $referer = null; if (array_key_exists(self::REFERER_KEY, $this->serverData)) { $referer = $this->serverData[self::REFERER_KEY]; } return $referer; }
php
public function getReferer() { $referer = null; if (array_key_exists(self::REFERER_KEY, $this->serverData)) { $referer = $this->serverData[self::REFERER_KEY]; } return $referer; }
Get the HTTP REFERER from the server data. @return string|null The referer or null if not found.
https://github.com/air-php/http/blob/213c02e537cea3d949cc8dbb1218c60c070fce8a/src/Request/Request.php#L176-L185
Tuna-CMS/tuna-bundle
src/Tuna/Bundle/TranslationBundle/Command/DeleteTranslationsCommand.php
DeleteTranslationsCommand.askConfirmation
private function askConfirmation(InputInterface $input, OutputInterface $output, $question, $default) { if (!class_exists(ConfirmationQuestion::class)) { $dialog = $this->getHelperSet()->get('dialog'); return $dialog->askConfirmation($output, $question, $default); } $questionHelper = $this->getHelperSet()->get('question'); $question = new ConfirmationQuestion($question, $default); return $questionHelper->ask($input, $output, $question); }
php
private function askConfirmation(InputInterface $input, OutputInterface $output, $question, $default) { if (!class_exists(ConfirmationQuestion::class)) { $dialog = $this->getHelperSet()->get('dialog'); return $dialog->askConfirmation($output, $question, $default); } $questionHelper = $this->getHelperSet()->get('question'); $question = new ConfirmationQuestion($question, $default); return $questionHelper->ask($input, $output, $question); }
@param InputInterface $input @param OutputInterface $output @param string $question @param bool $default @return bool
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/TranslationBundle/Command/DeleteTranslationsCommand.php#L44-L56
hummer2k/ConLayout
src/Zdt/Collector/LayoutCollector.php
LayoutCollector.collect
public function collect(MvcEvent $mvcEvent) { $layout = $mvcEvent->getViewModel(); $blocks = []; foreach ($this->layout->getBlocks() as $blockId => $block) { if ($parentBlock = $block->getOption('parent')) { $captureTo = $parentBlock . '::' . $block->captureTo(); } else { $captureTo = $block->captureTo(); } $blocks[$blockId] = [ 'instance' => $block, 'template' => $this->resolveTemplate($block->getTemplate()), 'capture_to' => $captureTo, 'class' => get_class($block) ]; } $data = [ 'handles' => $this->updater->getHandles(true), 'layout_structure' => $this->updater->getLayoutStructure()->toArray(), 'blocks' => $blocks, 'layout_template' => $layout->getTemplate(), 'current_area' => $this->updater->getArea() ]; $this->data = $data; return $this; }
php
public function collect(MvcEvent $mvcEvent) { $layout = $mvcEvent->getViewModel(); $blocks = []; foreach ($this->layout->getBlocks() as $blockId => $block) { if ($parentBlock = $block->getOption('parent')) { $captureTo = $parentBlock . '::' . $block->captureTo(); } else { $captureTo = $block->captureTo(); } $blocks[$blockId] = [ 'instance' => $block, 'template' => $this->resolveTemplate($block->getTemplate()), 'capture_to' => $captureTo, 'class' => get_class($block) ]; } $data = [ 'handles' => $this->updater->getHandles(true), 'layout_structure' => $this->updater->getLayoutStructure()->toArray(), 'blocks' => $blocks, 'layout_template' => $layout->getTemplate(), 'current_area' => $this->updater->getArea() ]; $this->data = $data; return $this; }
collect data for zdt @param MvcEvent $mvcEvent @return LayoutCollector
https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Zdt/Collector/LayoutCollector.php#L77-L104
hummer2k/ConLayout
src/Zdt/Collector/LayoutCollector.php
LayoutCollector.resolveTemplate
private function resolveTemplate($template) { $template = str_replace( getcwd(), '', $this->viewResolver->resolve($template) ); return $template; }
php
private function resolveTemplate($template) { $template = str_replace( getcwd(), '', $this->viewResolver->resolve($template) ); return $template; }
retrieve resolved template path @param string $template @return string
https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Zdt/Collector/LayoutCollector.php#L112-L120
alphacomm/alpharpc
src/AlphaRPC/Console/Command/PrepareCustomConfig.php
PrepareCustomConfig.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->copy('alpharpc_config.yml', $output); $this->copy('alpharpc_resources.yml', $output); $output->writeln(array( 'Done.', '<info>You can now edit alpharpc_*.yml config files.</info>', '', )); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->copy('alpharpc_config.yml', $output); $this->copy('alpharpc_resources.yml', $output); $output->writeln(array( 'Done.', '<info>You can now edit alpharpc_*.yml config files.</info>', '', )); }
{@inheritdoc}
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Console/Command/PrepareCustomConfig.php#L66-L76
phPoirot/Stream
ResourceStream.php
ResourceStream.meta
function meta() { if (!$this->_rMetaInfo) $this->_rMetaInfo = new MetaReaderOfPhpResource($this->getRHandler()); return $this->_rMetaInfo; }
php
function meta() { if (!$this->_rMetaInfo) $this->_rMetaInfo = new MetaReaderOfPhpResource($this->getRHandler()); return $this->_rMetaInfo; }
Meta Data About Handler @return MetaReaderOfPhpResource|iMetaReaderOfPhpResource
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/ResourceStream.php#L90-L96
phPoirot/Stream
ResourceStream.php
ResourceStream.appendFilter
function appendFilter(iFilterStream $filter, $rwFlag = STREAM_FILTER_ALL) { $filterRes = $filter->appendTo($this); // store attached filter resource, so we can remove it from stream handler later $this->attachedFilters[$filter->getLabel()] = $filterRes; return $this; }
php
function appendFilter(iFilterStream $filter, $rwFlag = STREAM_FILTER_ALL) { $filterRes = $filter->appendTo($this); // store attached filter resource, so we can remove it from stream handler later $this->attachedFilters[$filter->getLabel()] = $filterRes; return $this; }
Append Filter [code] $filter->appendTo($this) [/code] @param iFilterStream $filter @param int $rwFlag @see iSFilter::AppendTo @return $this
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/ResourceStream.php#L110-L117
phPoirot/Stream
ResourceStream.php
ResourceStream.prependFilter
function prependFilter(iFilterStream $filter, $rwFlag = STREAM_FILTER_ALL) { $filterRes = $filter->prependTo($this); // store attached filter resource, so we can remove it from stream handler later $this->attachedFilters[$filter->getLabel()] = $filterRes; return $this; }
php
function prependFilter(iFilterStream $filter, $rwFlag = STREAM_FILTER_ALL) { $filterRes = $filter->prependTo($this); // store attached filter resource, so we can remove it from stream handler later $this->attachedFilters[$filter->getLabel()] = $filterRes; return $this; }
Attach a filter to a stream @param iFilterStream $filter @param int $rwFlag @return $this
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/ResourceStream.php#L127-L134
phPoirot/Stream
ResourceStream.php
ResourceStream.removeFilter
function removeFilter(iFilterStream $filter) { $filterName = $filter->getLabel(); if (isset($this->attachedFilters[$filterName])) { $filterRes = $this->attachedFilters[$filterName]; stream_filter_remove($filterRes); unset($this->attachedFilters[$filterName]); // filter was removed } return $this; }
php
function removeFilter(iFilterStream $filter) { $filterName = $filter->getLabel(); if (isset($this->attachedFilters[$filterName])) { $filterRes = $this->attachedFilters[$filterName]; stream_filter_remove($filterRes); unset($this->attachedFilters[$filterName]); // filter was removed } return $this; }
Remove Given Filter From Resource @param iFilterStream $filter @return $this
https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/ResourceStream.php#L143-L154
austinkregel/formmodel
src/FormModel/Frameworks/Materialize.php
Materialize.select
public function select(array $configs, $options) { $label = (!empty($options['name']) ? ucwords($options['name']) : ''); return ' <div class="input-field"> '.parent::plainSelect(array_merge([ 'id' => $this->genId($label), ], $configs), $options).(empty($label) | (substr($label, 0, 1) == '_') ? '' : '<label for="'.$label.'">'.$this->inputToRead($label).'</label>').' </div> '; }
php
public function select(array $configs, $options) { $label = (!empty($options['name']) ? ucwords($options['name']) : ''); return ' <div class="input-field"> '.parent::plainSelect(array_merge([ 'id' => $this->genId($label), ], $configs), $options).(empty($label) | (substr($label, 0, 1) == '_') ? '' : '<label for="'.$label.'">'.$this->inputToRead($label).'</label>').' </div> '; }
Generate a select. @param array $configs @param mixed $options @return string
https://github.com/austinkregel/formmodel/blob/49943a8f563d2e9028f6bc992708e104f9be22e3/src/FormModel/Frameworks/Materialize.php#L57-L69
austinkregel/formmodel
src/FormModel/Frameworks/Materialize.php
Materialize.textarea
public function textarea(array $options, $text = '') { $label = (!empty($options['name']) ? ucwords($options['name']) : ''); return ' <div class="input-field"> '.parent::plainTextarea(array_merge([ 'class' => 'materialize-textarea', 'id' => $this->genId($label), ], $options), $text).' '.(empty($label) | (substr($label, 0, 1) == '_') ? '' : '<label for="'.$this->genId($label).'">'.$this->inputToRead($label).'</label>').' </div>'; }
php
public function textarea(array $options, $text = '') { $label = (!empty($options['name']) ? ucwords($options['name']) : ''); return ' <div class="input-field"> '.parent::plainTextarea(array_merge([ 'class' => 'materialize-textarea', 'id' => $this->genId($label), ], $options), $text).' '.(empty($label) | (substr($label, 0, 1) == '_') ? '' : '<label for="'.$this->genId($label).'">'.$this->inputToRead($label).'</label>').' </div>'; }
Generate a textarea. @param array $options @param string $text @return string
https://github.com/austinkregel/formmodel/blob/49943a8f563d2e9028f6bc992708e104f9be22e3/src/FormModel/Frameworks/Materialize.php#L79-L92
austinkregel/formmodel
src/FormModel/Frameworks/Materialize.php
Materialize.input
public function input(array $options) { $label = (!empty($options['name']) ? ucwords($options['name']) : ''); return ' <div class="input-field"> '.parent::plainInput(array_merge([ 'class' => 'validate', 'id' => $this->genId($label), ], $options)).(empty($label) | (substr($label, 0, 1) == '_') ? '' : '<label for="'.$this->genId($label).'">'.$this->inputToRead($label).'</label>').' </div> '; }
php
public function input(array $options) { $label = (!empty($options['name']) ? ucwords($options['name']) : ''); return ' <div class="input-field"> '.parent::plainInput(array_merge([ 'class' => 'validate', 'id' => $this->genId($label), ], $options)).(empty($label) | (substr($label, 0, 1) == '_') ? '' : '<label for="'.$this->genId($label).'">'.$this->inputToRead($label).'</label>').' </div> '; }
Generate an input area. @param array $options @return string
https://github.com/austinkregel/formmodel/blob/49943a8f563d2e9028f6bc992708e104f9be22e3/src/FormModel/Frameworks/Materialize.php#L101-L114
PhoxPHP/Glider
src/Model/Model.php
Model.addPropertyIf
final public function addPropertyIf(Bool $condition=null, String $property, $value=null) { if ($condition == true) { $this->softProperties[$property] = $value; } }
php
final public function addPropertyIf(Bool $condition=null, String $property, $value=null) { if ($condition == true) { $this->softProperties[$property] = $value; } }
Adds a property to list of soft properties if condition is true. @param $condition <Boolean> @param $property <String> @param $value <Mixed> @access public @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L193-L198
PhoxPHP/Glider
src/Model/Model.php
Model.addPropertyIfNot
final public function addPropertyIfNot(Bool $condition=null, String $property, $value=null) { if ($condition == false) { $this->softProperties[$property] = $value; } }
php
final public function addPropertyIfNot(Bool $condition=null, String $property, $value=null) { if ($condition == false) { $this->softProperties[$property] = $value; } }
Adds a property to list of soft properties if condition is false. @param $condition <Boolean> @param $property <String> @param $value <Mixed> @access public @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L209-L214
PhoxPHP/Glider
src/Model/Model.php
Model.hasSoftProperty
public static function hasSoftProperty(String $property=null) : Bool { return (isset($this->softProperties[$property])) ? true : false; }
php
public static function hasSoftProperty(String $property=null) : Bool { return (isset($this->softProperties[$property])) ? true : false; }
Checks if a property exists. @param $property <String> @access public @static @return <Boolean>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L240-L243
PhoxPHP/Glider
src/Model/Model.php
Model.getSoftProperties
public function getSoftProperties(Bool $asObject=false) { if ($asObject == true) { return (Object) $this->softProperties; } return $this->softProperties; }
php
public function getSoftProperties(Bool $asObject=false) { if ($asObject == true) { return (Object) $this->softProperties; } return $this->softProperties; }
Returns properties created using the __set magic method either as an array or an object if the @param $asObject is set to true. @param $asObject <Boolean> @access public @static @return <Mixed>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L254-L261
PhoxPHP/Glider
src/Model/Model.php
Model.find
final public function find(Int $key=null, Array $options=[]) : ModelContract { $model = Model::getInstanceOfModel(); $columns = $this->getAccessibleProperties(); $builder = $this->toSql($columns); $builder->where( $this->primaryKey(), $key ); $result = $builder->get(); if ($result->first()) { $first = $result->toArray()->first(); array_map(function($key) use ($first) { $this->softProperties[$key] = $first[$key]; }, array_keys($first)); } return $this; }
php
final public function find(Int $key=null, Array $options=[]) : ModelContract { $model = Model::getInstanceOfModel(); $columns = $this->getAccessibleProperties(); $builder = $this->toSql($columns); $builder->where( $this->primaryKey(), $key ); $result = $builder->get(); if ($result->first()) { $first = $result->toArray()->first(); array_map(function($key) use ($first) { $this->softProperties[$key] = $first[$key]; }, array_keys($first)); } return $this; }
{@inheritDoc}
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L266-L293
PhoxPHP/Glider
src/Model/Model.php
Model.all
final public function all() { $accessibleProperties = $this->accessibleProperties(); $results = []; $columns = $this->getAccessibleProperties(); $builder = $this->toSql(Attributes::ALL_SELECTOR); $result = $builder->get(); if ($result->size() > 0) { $resultArray = $result->toArray()->all(); foreach($resultArray as $i => $result) { $res = $resultArray[$i]; $accessible = []; foreach(array_keys($res) as $i => $key) { if ($this->isAccessible($key)) { $accessible[$key] = $res[$key]; } } $results[] = $accessible; } } return $results; }
php
final public function all() { $accessibleProperties = $this->accessibleProperties(); $results = []; $columns = $this->getAccessibleProperties(); $builder = $this->toSql(Attributes::ALL_SELECTOR); $result = $builder->get(); if ($result->size() > 0) { $resultArray = $result->toArray()->all(); foreach($resultArray as $i => $result) { $res = $resultArray[$i]; $accessible = []; foreach(array_keys($res) as $i => $key) { if ($this->isAccessible($key)) { $accessible[$key] = $res[$key]; } } $results[] = $accessible; } } return $results; }
{@inheritDoc}
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L298-L328
PhoxPHP/Glider
src/Model/Model.php
Model.hasRelation
public function hasRelation(String $label) : Bool { if (isset($this->relations[$label])) { return true; } return false; }
php
public function hasRelation(String $label) : Bool { if (isset($this->relations[$label])) { return true; } return false; }
Checks if model is related to another model. @param $label <String> @access public @return <Boolean>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L490-L497
PhoxPHP/Glider
src/Model/Model.php
Model.toSql
protected function toSql($fields=null) : QueryBuilder { $queryBuilder = $this->queryBuilder() ->select($fields) ->from($this->table); $orderBy = []; if (isset(Model::$findOptions['asc'])) { $orderBy[] = Model::$findOptions['asc'] . ' ASC'; } if (isset(Model::$findOptions['desc'])) { $orderBy[] = Model::$findOptions['desc'] . ' DESC'; } if (!empty($orderBy)) { $queryBuilder->orderBy($orderBy); } if (isset(Model::$findOptions['limit'])) { $limit = Model::$findOptions['limit']; if (is_array($limit) && count($limit) > 1) { $queryBuilder->limit($limit[0], $limit[1]); }else{ $queryBuilder->limit($limit); } } return $queryBuilder; }
php
protected function toSql($fields=null) : QueryBuilder { $queryBuilder = $this->queryBuilder() ->select($fields) ->from($this->table); $orderBy = []; if (isset(Model::$findOptions['asc'])) { $orderBy[] = Model::$findOptions['asc'] . ' ASC'; } if (isset(Model::$findOptions['desc'])) { $orderBy[] = Model::$findOptions['desc'] . ' DESC'; } if (!empty($orderBy)) { $queryBuilder->orderBy($orderBy); } if (isset(Model::$findOptions['limit'])) { $limit = Model::$findOptions['limit']; if (is_array($limit) && count($limit) > 1) { $queryBuilder->limit($limit[0], $limit[1]); }else{ $queryBuilder->limit($limit); } } return $queryBuilder; }
Returns a prepared query that will be used by other find methods. @param $fields <Mixed> @access protected @static @return <Object> <Kit\Glider\Query\Builder\QueryBuilder>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L507-L538
PhoxPHP/Glider
src/Model/Model.php
Model.getAccessibleProperties
protected function getAccessibleProperties(Array $with=[], Bool $addAccessibleProperties=true) : Array { $accessibleProperties = array_merge($this->accessibleProperties(), $with); if ($addAccessibleProperties == false) { $accessibleProperties = $with; } $properties = []; $associatedTable = $this->table; $properties = array_map(function($property) use ($associatedTable) { return $associatedTable . '.' . $property; }, $accessibleProperties); return $properties; }
php
protected function getAccessibleProperties(Array $with=[], Bool $addAccessibleProperties=true) : Array { $accessibleProperties = array_merge($this->accessibleProperties(), $with); if ($addAccessibleProperties == false) { $accessibleProperties = $with; } $properties = []; $associatedTable = $this->table; $properties = array_map(function($property) use ($associatedTable) { return $associatedTable . '.' . $property; }, $accessibleProperties); return $properties; }
Returns an array of accessible properties modified. This method accepts two arguments. The first argument is an array of columns that will be merged to the model's accessible properties, while the second argument accepts a boolean type value. It is default to true, if it is set to false, the model's accessible properties will be ignored and the columns in @param $with will be used instead. @param $with <Array> @param $addAccessibleProperties <Boolean> @access protected @return <Array>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L551-L567
PhoxPHP/Glider
src/Model/Model.php
Model.isAccessible
protected function isAccessible(String $property) : Bool { if (in_array($property, $this->accessibleProperties())) { return true; } return false; }
php
protected function isAccessible(String $property) : Bool { if (in_array($property, $this->accessibleProperties())) { return true; } return false; }
Checks if a property can be accessed. @param $property <String> @access protected @return <Boolean>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Model.php#L576-L583
alxmsl/Cli
source/CommandPosix.php
CommandPosix.getPostfix
private static function getPostfix(Option $Option) { $postfix = ''; if ($Option->getType() == Option::TYPE_STRING) { $postfix .= ':'; if (!$Option->isRequired()) { $postfix .= ':'; } } return $postfix; }
php
private static function getPostfix(Option $Option) { $postfix = ''; if ($Option->getType() == Option::TYPE_STRING) { $postfix .= ':'; if (!$Option->isRequired()) { $postfix .= ':'; } } return $postfix; }
Method to build getopt parameter postfix for option @param Option $Option instance of option @return string getopt parameter postfix for option
https://github.com/alxmsl/Cli/blob/806fc2baa23e5a3d32734a4b913c3730342a8bb1/source/CommandPosix.php#L39-L48
alxmsl/Cli
source/CommandPosix.php
CommandPosix.getOptionsSearchStrings
private function getOptionsSearchStrings() { if (empty($this->searchStringsCache)) { $this->searchStringsCache = array( 0 => '', 1 => array(), ); foreach ($this->parameters as $Option) { $postfix = self::getPostfix($Option); /** @var $Option Option */ $this->searchStringsCache[0] .= $Option->getShort() . $postfix; $this->searchStringsCache[1][] = $Option->getLong() . $postfix; } } return $this->searchStringsCache; }
php
private function getOptionsSearchStrings() { if (empty($this->searchStringsCache)) { $this->searchStringsCache = array( 0 => '', 1 => array(), ); foreach ($this->parameters as $Option) { $postfix = self::getPostfix($Option); /** @var $Option Option */ $this->searchStringsCache[0] .= $Option->getShort() . $postfix; $this->searchStringsCache[1][] = $Option->getLong() . $postfix; } } return $this->searchStringsCache; }
Method to get getopt parameters for command line parsing @return array getopt parameters
https://github.com/alxmsl/Cli/blob/806fc2baa23e5a3d32734a4b913c3730342a8bb1/source/CommandPosix.php#L54-L68
alxmsl/Cli
source/CommandPosix.php
CommandPosix.parse
public function parse($panic = false) { list($shorts, $longs) = $this->getOptionsSearchStrings(); $options = getopt($shorts, $longs); $Exception = null; foreach ($this->parameters as $Option) { /** @var $Option Option */ $short = $Option->getShort(); $long = $Option->getLong(); switch (true) { case isset($options[$short]) && isset($options[$long]): throw new DuplicateOptionException(); case isset($options[$short]): $this->setOptionValue($Option, $this->getPreparedValue($options[$short])); break; case isset($options[$long]): $this->setOptionValue($Option, $this->getPreparedValue($options[$long])); break; case $Option->isRequired(): $Exception = new RequiredOptionException($long); } } if ($panic && !is_null($Exception)) { throw $Exception; } }
php
public function parse($panic = false) { list($shorts, $longs) = $this->getOptionsSearchStrings(); $options = getopt($shorts, $longs); $Exception = null; foreach ($this->parameters as $Option) { /** @var $Option Option */ $short = $Option->getShort(); $long = $Option->getLong(); switch (true) { case isset($options[$short]) && isset($options[$long]): throw new DuplicateOptionException(); case isset($options[$short]): $this->setOptionValue($Option, $this->getPreparedValue($options[$short])); break; case isset($options[$long]): $this->setOptionValue($Option, $this->getPreparedValue($options[$long])); break; case $Option->isRequired(): $Exception = new RequiredOptionException($long); } } if ($panic && !is_null($Exception)) { throw $Exception; } }
POSIX parse command line method @param bool $panic throw exception about required option absence @throws DuplicateOptionException when option value duplicated @throws RequiredOptionException when required options is not set
https://github.com/alxmsl/Cli/blob/806fc2baa23e5a3d32734a4b913c3730342a8bb1/source/CommandPosix.php#L92-L117
alxmsl/Cli
source/CommandPosix.php
CommandPosix.displayHelp
public function displayHelp() { $string = 'Using: ' . $this->script . ' ' . $this->command . ' '; $where = array(); foreach ($this->parameters as $Option) { /** @var $Option Option */ $short = $Option->getShort(); $long = $Option->getLong(); $temp = '-' . $short . '|--' . $long; if (!$Option->isRequired()) { $string .= '[' . $temp . '] '; } else { $string .= $temp . ' '; } $where[] = '-' . $short . ', --' . $long . ' - ' . $Option->getDescription(); } $string .= "\n"; $string .= implode("\n", $where) . "\n"; echo $string; exit(0); }
php
public function displayHelp() { $string = 'Using: ' . $this->script . ' ' . $this->command . ' '; $where = array(); foreach ($this->parameters as $Option) { /** @var $Option Option */ $short = $Option->getShort(); $long = $Option->getLong(); $temp = '-' . $short . '|--' . $long; if (!$Option->isRequired()) { $string .= '[' . $temp . '] '; } else { $string .= $temp . ' '; } $where[] = '-' . $short . ', --' . $long . ' - ' . $Option->getDescription(); } $string .= "\n"; $string .= implode("\n", $where) . "\n"; echo $string; exit(0); }
Display command help
https://github.com/alxmsl/Cli/blob/806fc2baa23e5a3d32734a4b913c3730342a8bb1/source/CommandPosix.php#L122-L142
alxmsl/Cli
source/CommandPosix.php
CommandPosix.setOptionValue
private function setOptionValue(Option $Option, $value) { $Option->setValue($value); $long = $Option->getLong(); if (isset($this->events[$long])) { $Handler = $this->events[$long]; $Handler($long, $value); } }
php
private function setOptionValue(Option $Option, $value) { $Option->setValue($value); $long = $Option->getLong(); if (isset($this->events[$long])) { $Handler = $this->events[$long]; $Handler($long, $value); } }
Method to set option value and call event handler if needed @param Option $Option instance of option @param bool|string $value option value
https://github.com/alxmsl/Cli/blob/806fc2baa23e5a3d32734a4b913c3730342a8bb1/source/CommandPosix.php#L149-L156
atelierspierrot/templatengine
src/Assets/Composer/TemplateEngineAutoloadGenerator.php
TemplateEngineAutoloadGenerator.parseComposerExtra
public function parseComposerExtra(PackageInterface $package, $assets_package_dir, $vendor_package_dir) { $data = $this->_autoloader->getAssetsInstaller()->parseComposerExtra($package, $assets_package_dir); if (is_null($data)) { $data = array(); } $extra = $package->getExtra(); $assets_package_dir = rtrim($assets_package_dir, '/') . '/'; if (strlen($vendor_package_dir)) { $vendor_package_dir = rtrim($vendor_package_dir, '/') . '/'; } $mapping = array( 'layouts'=>'layouts_path', 'views'=>'views_path', 'views-functions'=>'views_functions' ); foreach ($mapping as $json_name=>$var_name) { if (isset($extra[$json_name])) { $json_vals = is_array($extra[$json_name]) ? $extra[$json_name] : array($extra[$json_name]); $data[$var_name] = array(); foreach ($json_vals as $json_val) { $data[$var_name][] = $vendor_package_dir . $json_val; } } } /* if (isset($extra['layouts'])) { $layouts = is_array($extra['layouts']) ? $extra['layouts'] : array($extra['layouts']); $data['layouts_path'] = array(); foreach ($layouts as $layout_path) { $data['layouts_path'][] = $vendor_package_dir . $layout_path; } } if (isset($extra['views'])) { $views = is_array($extra['views']) ? $extra['views'] : array($extra['views']); $data['views_path'] = array(); foreach ($views as $view_path) { $data['views_path'][] = $vendor_package_dir . $view_path; } } if (isset($extra['views-functions'])) { $views_fcts = is_array($extra['views-functions']) ? $extra['views-functions'] : array($extra['views-functions']); $data['views_functions'] = array(); foreach ($views_fcts as $view_fct_path) { $data['views_functions'][] = $vendor_package_dir . $view_fct_path; } } */ return !empty($data) ? $data : null; }
php
public function parseComposerExtra(PackageInterface $package, $assets_package_dir, $vendor_package_dir) { $data = $this->_autoloader->getAssetsInstaller()->parseComposerExtra($package, $assets_package_dir); if (is_null($data)) { $data = array(); } $extra = $package->getExtra(); $assets_package_dir = rtrim($assets_package_dir, '/') . '/'; if (strlen($vendor_package_dir)) { $vendor_package_dir = rtrim($vendor_package_dir, '/') . '/'; } $mapping = array( 'layouts'=>'layouts_path', 'views'=>'views_path', 'views-functions'=>'views_functions' ); foreach ($mapping as $json_name=>$var_name) { if (isset($extra[$json_name])) { $json_vals = is_array($extra[$json_name]) ? $extra[$json_name] : array($extra[$json_name]); $data[$var_name] = array(); foreach ($json_vals as $json_val) { $data[$var_name][] = $vendor_package_dir . $json_val; } } } /* if (isset($extra['layouts'])) { $layouts = is_array($extra['layouts']) ? $extra['layouts'] : array($extra['layouts']); $data['layouts_path'] = array(); foreach ($layouts as $layout_path) { $data['layouts_path'][] = $vendor_package_dir . $layout_path; } } if (isset($extra['views'])) { $views = is_array($extra['views']) ? $extra['views'] : array($extra['views']); $data['views_path'] = array(); foreach ($views as $view_path) { $data['views_path'][] = $vendor_package_dir . $view_path; } } if (isset($extra['views-functions'])) { $views_fcts = is_array($extra['views-functions']) ? $extra['views-functions'] : array($extra['views-functions']); $data['views_functions'] = array(); foreach ($views_fcts as $view_fct_path) { $data['views_functions'][] = $vendor_package_dir . $view_fct_path; } } */ return !empty($data) ? $data : null; }
Parse the `composer.json` "extra" block of a package and return its transformed data @param \Composer\Package\PackageInterface $package @param string $assets_package_dir @param string $vendor_package_dir @return array|null
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Composer/TemplateEngineAutoloadGenerator.php#L143-L195
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.init
protected function init() { if (true===$this->isInited) { return; } $this->_cleanFilesStack(); if (empty($this->__adapter_type)) { $this->_guessAdapterType(); } if (!empty($this->__adapter_type)) { if (class_exists($this->__adapter_type)) { $this->__adapter = new $this->__adapter_type; if (!($this->__adapter instanceof AbstractCompressorAdapter)) { throw new \LogicException( sprintf('Compressor adapter must extend class "%s" (having object "%s")!', "Assets\AbstractCompressorAdapter", $this->__adapter_type) ); } } else { throw new \RuntimeException( sprintf('Compressor adapter for type "%s" doesn\'t exist!', $this->__adapter_type) ); } } $this->isInited = true; }
php
protected function init() { if (true===$this->isInited) { return; } $this->_cleanFilesStack(); if (empty($this->__adapter_type)) { $this->_guessAdapterType(); } if (!empty($this->__adapter_type)) { if (class_exists($this->__adapter_type)) { $this->__adapter = new $this->__adapter_type; if (!($this->__adapter instanceof AbstractCompressorAdapter)) { throw new \LogicException( sprintf('Compressor adapter must extend class "%s" (having object "%s")!', "Assets\AbstractCompressorAdapter", $this->__adapter_type) ); } } else { throw new \RuntimeException( sprintf('Compressor adapter for type "%s" doesn\'t exist!', $this->__adapter_type) ); } } $this->isInited = true; }
Initialization : creation of the adapter @throws \RuntimeException if the adapter doesn't exist
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L124-L152
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.reset
public function reset($hard = false) { $this->files_stack = array(); $this->contents = array(); $this->silent = true; $this->direct_output = false; $this->isCleaned_files_stack = false; $this->isInited = false; if (true===$hard) { $this->raw_header = ''; $this->destination_dir = ''; $this->web_root_path = null; $this->__adapter_type = null; $this->__adapter_action = 'merge'; $this->__adapter = null; } $this->resetOutput(); return $this; }
php
public function reset($hard = false) { $this->files_stack = array(); $this->contents = array(); $this->silent = true; $this->direct_output = false; $this->isCleaned_files_stack = false; $this->isInited = false; if (true===$hard) { $this->raw_header = ''; $this->destination_dir = ''; $this->web_root_path = null; $this->__adapter_type = null; $this->__adapter_action = 'merge'; $this->__adapter = null; } $this->resetOutput(); return $this; }
Reset all object properties to default or empty values @param bool $hard Reset all object properties (destination directory and web root included) @return self
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L160-L178
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.setAdapterAction
public function setAdapterAction($action) { if (true===$this->isInited) { $this->resetOutput(); } $this->__adapter_action = $action; return $this; }
php
public function setAdapterAction($action) { if (true===$this->isInited) { $this->resetOutput(); } $this->__adapter_action = $action; return $this; }
Set the adapter action to process and reset the output @param string $action The action name @return self
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L239-L246
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.addContent
public function addContent($str, $index = null) { if (!is_null($index)) { $this->contents[$index] = $str; } else { $this->contents[] = $str; } return $this; }
php
public function addContent($str, $index = null) { if (!is_null($index)) { $this->contents[$index] = $str; } else { $this->contents[] = $str; } return $this; }
Add a raw content to treat @param string $str the content to add @param null/string $index the content index @return self
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L279-L287
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.setDestinationFile
public function setDestinationFile($destination_file) { if (is_string($destination_file)) { $this->destination_file = $destination_file; } else { if (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Destination file name must be a string (got "%s")!', gettype($destination_file)) ); } } return $this; }
php
public function setDestinationFile($destination_file) { if (is_string($destination_file)) { $this->destination_file = $destination_file; } else { if (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Destination file name must be a string (got "%s")!', gettype($destination_file)) ); } } return $this; }
Set the destination file to write the result in @param string $destination_file The file path or name to create and write in @return self @throws \InvalidArgumentException if the file name is not a string (and if $silent==false)
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L351-L363
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.guessDestinationFilename
public function guessDestinationFilename() { if (!empty($this->files_stack)) { $this->_cleanFilesStack(); $this->init(); $_fs = array(); foreach ($this->files_stack as $_file) { $_fs[] = $_file->getFilename(); } if (!empty($_fs)) { sort($_fs); $this->setDestinationFile( md5(join('', $_fs)) .'_'.$this->__adapter_action .'.'.$this->__adapter->file_extension ); return $this->getDestinationFile(); } } if (false===$this->silent) { throw new \RuntimeException( '[Compressor] Destination filename can\'t be guessed because files stack is empty!' ); } return null; }
php
public function guessDestinationFilename() { if (!empty($this->files_stack)) { $this->_cleanFilesStack(); $this->init(); $_fs = array(); foreach ($this->files_stack as $_file) { $_fs[] = $_file->getFilename(); } if (!empty($_fs)) { sort($_fs); $this->setDestinationFile( md5(join('', $_fs)) .'_'.$this->__adapter_action .'.'.$this->__adapter->file_extension ); return $this->getDestinationFile(); } } if (false===$this->silent) { throw new \RuntimeException( '[Compressor] Destination filename can\'t be guessed because files stack is empty!' ); } return null; }
Build a destination filename based on the files stack names @return string The file name built @throws \RuntimeException if the files stack is empty (filename can not be guessed)
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L381-L407
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.setDestinationDir
public function setDestinationDir($destination_dir) { if (is_string($destination_dir)) { $destination_dir = realpath($destination_dir); if (@file_exists($destination_dir) && @is_dir($destination_dir)) { $this->destination_dir = rtrim($destination_dir, '/').'/'; } elseif (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Destination directory "%s" must exist!', $destination_dir) ); } } else { if (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Destination directory must be a string (got "%s")!', gettype($destination_dir)) ); } } return $this; }
php
public function setDestinationDir($destination_dir) { if (is_string($destination_dir)) { $destination_dir = realpath($destination_dir); if (@file_exists($destination_dir) && @is_dir($destination_dir)) { $this->destination_dir = rtrim($destination_dir, '/').'/'; } elseif (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Destination directory "%s" must exist!', $destination_dir) ); } } else { if (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Destination directory must be a string (got "%s")!', gettype($destination_dir)) ); } } return $this; }
Set the destination directory to write the destination file in @param string $destination_dir The directory path to create the file in @return self @throws \InvalidArgumentException if the directory name is not a string (and if $silent==false)
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L416-L435
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.setWebRootPath
public function setWebRootPath($path) { if (is_string($path)) { $path = realpath($path); if (@file_exists($path) && @is_dir($path)) { $this->web_root_path = rtrim($path, '/').'/'; } elseif (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Web root path "%s" must exist!', $path) ); } } else { if (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Web root path must be a string (got "%s")!', gettype($path)) ); } } return $this; }
php
public function setWebRootPath($path) { if (is_string($path)) { $path = realpath($path); if (@file_exists($path) && @is_dir($path)) { $this->web_root_path = rtrim($path, '/').'/'; } elseif (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Web root path "%s" must exist!', $path) ); } } else { if (false===$this->silent) { throw new \InvalidArgumentException( sprintf('[Compressor] Web root path must be a string (got "%s")!', gettype($path)) ); } } return $this; }
Set the web root path (the real path to clear in DestinationRealPath) to build web path of destination file @param string $path The realpath of the web root to clear it from DestinationRealPath to build DestinationWebPath @return self @throws \InvalidArgumentException
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L454-L473
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.getDestinationWebPath
public function getDestinationWebPath() { if (!empty($this->web_root_path)) { return str_replace($this->web_root_path, '', $this->getDestinationRealPath()); } elseif (false===$this->silent) { throw new \LogicException( '[Compressor] Can\'t create web path because "web_root_path" is not defined!' ); } return null; }
php
public function getDestinationWebPath() { if (!empty($this->web_root_path)) { return str_replace($this->web_root_path, '', $this->getDestinationRealPath()); } elseif (false===$this->silent) { throw new \LogicException( '[Compressor] Can\'t create web path because "web_root_path" is not defined!' ); } return null; }
Get the destination file path ready for web inclusion @return string The file path to write in @throws \LogicException if the web root path has not been set (and silent==false)
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L491-L501
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.mustRefresh
public function mustRefresh() { if ($this->fileExists()) { $this->_cleanFilesStack(); $_dest = new \SplFileInfo($this->getDestinationRealPath()); if (!empty($this->files_stack)) { foreach ($this->files_stack as $_file) { if ($_file->getMTime() > $_dest->getMTime()) { return true; } } return false; } } return true; }
php
public function mustRefresh() { if ($this->fileExists()) { $this->_cleanFilesStack(); $_dest = new \SplFileInfo($this->getDestinationRealPath()); if (!empty($this->files_stack)) { foreach ($this->files_stack as $_file) { if ($_file->getMTime() > $_dest->getMTime()) { return true; } } return false; } } return true; }
Check if a destination file already exist for the current object and if it is fresher than sources @return bool True if the sources had been modified after minified file creation
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L531-L546
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.prepare
public function prepare() { $files = $this->getFilesStack(); if (!empty($files)) { foreach ($files as $_file) { $this->addContent( file_get_contents($_file->getRealPath()), $_file->getPathname() ); } } }
php
public function prepare() { $files = $this->getFilesStack(); if (!empty($files)) { foreach ($files as $_file) { $this->addContent( file_get_contents($_file->getRealPath()), $_file->getPathname() ); } } }
Prepare the current files/contents stack by populating the contents if needed @return self
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L557-L568
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor.process
public function process() { $this->_cleanFilesStack(); $this->init(); if (empty($this->destination_file) && false===$this->direct_output) { $this->guessDestinationFilename(); } if (!method_exists($this->__adapter, $this->__adapter_action)) { throw new \RuntimeException( sprintf('[Compressor] Action "%s" doesn\'t exist in "%s" adapter!', $this->__adapter_action, get_class($this->__adapter)) ); } if (false===$this->direct_output) { if (!$this->mustRefresh()) { $this->output = file_get_contents($this->getDestinationRealPath()); return $this; } } $this->prepare(); $stack = $this->getContents(); $contents = array(); foreach ($stack as $_name=>$_content) { $contents[] = ''; $contents[] = $this->__adapter->buildComment($_name); $contents[] = $this->__adapter->{$this->__adapter_action}($_content); } if (!empty($this->raw_header)) { $this->output = $this->raw_header."\n"; } $this->output .= implode("\n", $contents); if (!empty($this->output) && false===$this->direct_output) { $this->_writeDestinationFile(); } return strlen($this->output); }
php
public function process() { $this->_cleanFilesStack(); $this->init(); if (empty($this->destination_file) && false===$this->direct_output) { $this->guessDestinationFilename(); } if (!method_exists($this->__adapter, $this->__adapter_action)) { throw new \RuntimeException( sprintf('[Compressor] Action "%s" doesn\'t exist in "%s" adapter!', $this->__adapter_action, get_class($this->__adapter)) ); } if (false===$this->direct_output) { if (!$this->mustRefresh()) { $this->output = file_get_contents($this->getDestinationRealPath()); return $this; } } $this->prepare(); $stack = $this->getContents(); $contents = array(); foreach ($stack as $_name=>$_content) { $contents[] = ''; $contents[] = $this->__adapter->buildComment($_name); $contents[] = $this->__adapter->{$this->__adapter_action}($_content); } if (!empty($this->raw_header)) { $this->output = $this->raw_header."\n"; } $this->output .= implode("\n", $contents); if (!empty($this->output) && false===$this->direct_output) { $this->_writeDestinationFile(); } return strlen($this->output); }
Process the current files stack @return self @throws \RuntimeException
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L576-L615
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor._cleanFilesStack
protected function _cleanFilesStack() { if (true===$this->isCleaned_files_stack) { return; } $new_stack = array(); foreach ($this->files_stack as $_file) { if (is_object($_file) && ($_file instanceof \SplFileInfo)) { $new_stack[] = $_file; } elseif (is_string($_file) && @file_exists($_file)) { $new_stack[] = new \SplFileInfo($_file); } elseif (false===$this->silent) { throw new \RuntimeException( sprintf('[Compressor] Source to process "%s" not found!', $_file) ); } } $this->files_stack = $new_stack; $this->isCleaned_files_stack = true; }
php
protected function _cleanFilesStack() { if (true===$this->isCleaned_files_stack) { return; } $new_stack = array(); foreach ($this->files_stack as $_file) { if (is_object($_file) && ($_file instanceof \SplFileInfo)) { $new_stack[] = $_file; } elseif (is_string($_file) && @file_exists($_file)) { $new_stack[] = new \SplFileInfo($_file); } elseif (false===$this->silent) { throw new \RuntimeException( sprintf('[Compressor] Source to process "%s" not found!', $_file) ); } } $this->files_stack = $new_stack; $this->isCleaned_files_stack = true; }
Rebuild the current files stack as an array of File objects @return void @throws \RuntimeException if one of the files stack doesn't exist (and if $silent==false)
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L659-L679
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor._guessAdapterType
protected function _guessAdapterType() { $this->_cleanFilesStack(); if (!empty($this->files_stack)) { $_fs = $this->files_stack; $_file = array_shift($_fs); $this->setAdapterType($_file->getExtension()); return true; } elseif (false===$this->silent) { throw new \RuntimeException( '[Compressor] Trying to guess adapter from an empty files stack!' ); } return false; }
php
protected function _guessAdapterType() { $this->_cleanFilesStack(); if (!empty($this->files_stack)) { $_fs = $this->files_stack; $_file = array_shift($_fs); $this->setAdapterType($_file->getExtension()); return true; } elseif (false===$this->silent) { throw new \RuntimeException( '[Compressor] Trying to guess adapter from an empty files stack!' ); } return false; }
Guess the adapter type based on extension of the first file in stack @return bool True if the adapter type had been guessed @throws \RuntimeException if no file was found in the stack
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L687-L701
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor._writeDestinationFile
protected function _writeDestinationFile() { if (empty($this->destination_file)) { $this->guessDestinationFilename(); } $content = $this->_getHeaderComment()."\n".$this->output; $dest_file = $this->getDestinationRealPath(); if (false!==file_put_contents($dest_file, $content)) { return true; } else { if (false===$this->silent) { throw new \RuntimeException( sprintf('[Compressor] Destination compressed file "%s" can\'t be written on disk!', $dest_file) ); } return false; } }
php
protected function _writeDestinationFile() { if (empty($this->destination_file)) { $this->guessDestinationFilename(); } $content = $this->_getHeaderComment()."\n".$this->output; $dest_file = $this->getDestinationRealPath(); if (false!==file_put_contents($dest_file, $content)) { return true; } else { if (false===$this->silent) { throw new \RuntimeException( sprintf('[Compressor] Destination compressed file "%s" can\'t be written on disk!', $dest_file) ); } return false; } }
Writes the compressed content in the destination file @return bool|string The filename if it has been created, false otherwise @throws \RuntimeException if the file can't be written
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L713-L731
atelierspierrot/templatengine
src/Assets/Compressor.php
Compressor._getHeaderComment
protected function _getHeaderComment() { $this->init(); return $this->__adapter->buildComment( sprintf('Generated by %s class on %s at %s', __CLASS__, date('Y-m-d'), date('H:i')) ); }
php
protected function _getHeaderComment() { $this->init(); return $this->__adapter->buildComment( sprintf('Generated by %s class on %s at %s', __CLASS__, date('Y-m-d'), date('H:i')) ); }
Build the compressed content header comment information @return string A comment string to write in top of the content
https://github.com/atelierspierrot/templatengine/blob/de01b117f882670bed7b322e2d3b8b30fa9ae45f/src/Assets/Compressor.php#L738-L744
CanalTP/fenrir-api-client
src/AbstractGuzzle/Version/Guzzle3.php
Guzzle3.send
public function send(Request $request) { $guzzleRequest = $this->client->createRequest( $request->getMethod(), $request->getUri(), $request->getHeaders(), $request->getBody() ); $guzzleResponse = $guzzleRequest->send(); $response = new Response( $guzzleResponse->getStatusCode(), $guzzleResponse->getHeaders()->toArray(), $guzzleResponse->getBody(true) ); return $response; }
php
public function send(Request $request) { $guzzleRequest = $this->client->createRequest( $request->getMethod(), $request->getUri(), $request->getHeaders(), $request->getBody() ); $guzzleResponse = $guzzleRequest->send(); $response = new Response( $guzzleResponse->getStatusCode(), $guzzleResponse->getHeaders()->toArray(), $guzzleResponse->getBody(true) ); return $response; }
{@InheritDoc}
https://github.com/CanalTP/fenrir-api-client/blob/d279c2d91eea6f5077d488879e3f66ba9dbff367/src/AbstractGuzzle/Version/Guzzle3.php#L63-L81
BenGorFile/FileBundle
src/BenGorFile/FileBundle/DependencyInjection/Compiler/TwigPass.php
TwigPass.process
public function process(ContainerBuilder $container) { if (!$container->hasDefinition('bengor_file.file_bundle.twig.download_extension')) { return; } $config = $container->getParameter('bengor_file.config'); $handlers = []; foreach ($config['file_class'] as $key => $file) { $handlers[$key] = $container->getDefinition('bengor.file.application.query.' . $key . '_of_id'); } $container->getDefinition('bengor_file.file_bundle.twig.download_extension')->replaceArgument( 1, $handlers ); }
php
public function process(ContainerBuilder $container) { if (!$container->hasDefinition('bengor_file.file_bundle.twig.download_extension')) { return; } $config = $container->getParameter('bengor_file.config'); $handlers = []; foreach ($config['file_class'] as $key => $file) { $handlers[$key] = $container->getDefinition('bengor.file.application.query.' . $key . '_of_id'); } $container->getDefinition('bengor_file.file_bundle.twig.download_extension')->replaceArgument( 1, $handlers ); }
{@inheritdoc}
https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/DependencyInjection/Compiler/TwigPass.php#L28-L45
acacha/forge-publish
src/Console/Commands/Traits/InteractsWithLocalGithub.php
InteractsWithLocalGithub.getRepoFromGithubConfig
protected function getRepoFromGithubConfig() { $remote = `git remote get-url origin 2> /dev/null`; if (! starts_with($remote, ['[email protected]:','https://github.com/'])) { return ''; } if (starts_with($remote, '[email protected]:')) { // [email protected]:acacha/forge-publish.git return explode('.', explode(":", $remote)[1])[0]; } if (starts_with($remote, 'https://github.com/')) { // https://github.com/acacha/llum.git return explode('.', str_replace('https://github.com/', '', $remote))[0]; } }
php
protected function getRepoFromGithubConfig() { $remote = `git remote get-url origin 2> /dev/null`; if (! starts_with($remote, ['[email protected]:','https://github.com/'])) { return ''; } if (starts_with($remote, '[email protected]:')) { // [email protected]:acacha/forge-publish.git return explode('.', explode(":", $remote)[1])[0]; } if (starts_with($remote, 'https://github.com/')) { // https://github.com/acacha/llum.git return explode('.', str_replace('https://github.com/', '', $remote))[0]; } }
Get github repo from github. @return string
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/Traits/InteractsWithLocalGithub.php#L17-L32
pmdevelopment/tool-bundle
Framework/Utilities/CryptUtility.php
CryptUtility.encrypt
public static function encrypt($sValue, $sSecretKey, $migration = false) { if (empty($sValue)) { return ""; } if (true === $migration) { $sSecretKey = substr($sSecretKey, 0, 30) . "\0\0"; } else { $sSecretKey = substr($sSecretKey, 0, 32); } return rtrim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))), "\0"); }
php
public static function encrypt($sValue, $sSecretKey, $migration = false) { if (empty($sValue)) { return ""; } if (true === $migration) { $sSecretKey = substr($sSecretKey, 0, 30) . "\0\0"; } else { $sSecretKey = substr($sSecretKey, 0, 32); } return rtrim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))), "\0"); }
Encrypt Value by Key @param string $sValue @param string $sSecretKey @param bool $migration Use old buggy key or not @return string
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Utilities/CryptUtility.php#L27-L41
pmdevelopment/tool-bundle
Framework/Utilities/CryptUtility.php
CryptUtility.decrypt
public static function decrypt($sValue, $sSecretKey, $migration = false) { if (empty($sValue)) { return ""; } if (true === $migration) { $sSecretKey = substr($sSecretKey, 0, 30) . "\0\0"; } else { $sSecretKey = substr($sSecretKey, 0, 32); } return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)), "\0"); }
php
public static function decrypt($sValue, $sSecretKey, $migration = false) { if (empty($sValue)) { return ""; } if (true === $migration) { $sSecretKey = substr($sSecretKey, 0, 30) . "\0\0"; } else { $sSecretKey = substr($sSecretKey, 0, 32); } return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)), "\0"); }
Decrypt value by key @param string $sValue @param string $sSecretKey @param bool $migration Use old buggy key or not @return string
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Utilities/CryptUtility.php#L52-L65
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/ManyToOne.php
ManyToOne.initBySetting
public function initBySetting($model, $setting) { parent::initBySetting($model, $setting); if (is_array($setting)) { if (isset($setting['remote_class_type'])) { $this->remoteModelType = $setting['remote_class_type']; } } }
php
public function initBySetting($model, $setting) { parent::initBySetting($model, $setting); if (is_array($setting)) { if (isset($setting['remote_class_type'])) { $this->remoteModelType = $setting['remote_class_type']; } } }
/* CONSTRUCTOR ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/ManyToOne.php#L20-L28
laraplug/theme-module
Support/Traits/Dateable.php
Dateable.asDateTime
protected function asDateTime($value) { // If this value is already a Carbon instance, we shall just return it as is. // This prevents us having to re-instantiate a Carbon instance when we know // it already is one, which wouldn't be fulfilled by the DateTime check. if ($value instanceof Carbon) { return Date::parse($value); } if ($value instanceof Date) { return $value; } // If the value is already a DateTime instance, we will just skip the rest of // these checks since they will be a waste of time, and hinder performance // when checking the field. We will just return the DateTime right away. if ($value instanceof DateTimeInterface) { return new Date( $value->format('Y-m-d H:i:s.u'), $value->getTimeZone() ); } // If this value is an integer, we will assume it is a UNIX timestamp's value // and format a Carbon object from this timestamp. This allows flexibility // when defining your date fields as they might be UNIX timestamps here. if (is_numeric($value)) { return Date::createFromTimestamp($value); } // If the value is in simply year, month, day format, we will instantiate the // Carbon instances from that format. Again, this provides for simple date // fields on the database, while still supporting Carbonized conversion. if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value)) { return Date::createFromFormat('Y-m-d', $value)->startOfDay(); } // Finally, we will just assume this date is in the format used by default on // the database connection and use that format to create the Carbon object // that is returned back out to the developers after we convert it here. return Date::createFromFormat($this->getDateFormat(), $value); }
php
protected function asDateTime($value) { // If this value is already a Carbon instance, we shall just return it as is. // This prevents us having to re-instantiate a Carbon instance when we know // it already is one, which wouldn't be fulfilled by the DateTime check. if ($value instanceof Carbon) { return Date::parse($value); } if ($value instanceof Date) { return $value; } // If the value is already a DateTime instance, we will just skip the rest of // these checks since they will be a waste of time, and hinder performance // when checking the field. We will just return the DateTime right away. if ($value instanceof DateTimeInterface) { return new Date( $value->format('Y-m-d H:i:s.u'), $value->getTimeZone() ); } // If this value is an integer, we will assume it is a UNIX timestamp's value // and format a Carbon object from this timestamp. This allows flexibility // when defining your date fields as they might be UNIX timestamps here. if (is_numeric($value)) { return Date::createFromTimestamp($value); } // If the value is in simply year, month, day format, we will instantiate the // Carbon instances from that format. Again, this provides for simple date // fields on the database, while still supporting Carbonized conversion. if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value)) { return Date::createFromFormat('Y-m-d', $value)->startOfDay(); } // Finally, we will just assume this date is in the format used by default on // the database connection and use that format to create the Carbon object // that is returned back out to the developers after we convert it here. return Date::createFromFormat($this->getDateFormat(), $value); }
Return a timestamp as DateTime object. @param mixed $value @return Date
https://github.com/laraplug/theme-module/blob/b118e5a90aba61e9de2607be2385a8faccdc9b7f/Support/Traits/Dateable.php#L26-L61
3ev/wordpress-core
src/Tev/Post/Model/AbstractPost.php
AbstractPost.getContent
public function getContent() { $content = $this->getRawContent(); $content = apply_filters('the_content', $content); $content = str_replace( ']]>', ']]&gt;', $content); return $content; }
php
public function getContent() { $content = $this->getRawContent(); $content = apply_filters('the_content', $content); $content = str_replace( ']]>', ']]&gt;', $content); return $content; }
Get the post content, formatted as HTML. @return string
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Post/Model/AbstractPost.php#L207-L214
3ev/wordpress-core
src/Tev/Post/Model/AbstractPost.php
AbstractPost.getExcerpt
public function getExcerpt($content = null) { $raw = $exc = $this->base->post_excerpt; if (!strlen($exc)) { $exc = $content === null ? $this->getRawContent() : $content; $exc = strip_shortcodes($exc); $exc = apply_filters('the_content', $exc); $exc = str_replace(']]>', ']]&gt;', $exc); $exc = wp_trim_words( $exc, apply_filters('excerpt_length', 55), apply_filters('excerpt_more', ' ' . '[&hellip;]') ); } return apply_filters('wp_trim_excerpt', $exc, $raw); }
php
public function getExcerpt($content = null) { $raw = $exc = $this->base->post_excerpt; if (!strlen($exc)) { $exc = $content === null ? $this->getRawContent() : $content; $exc = strip_shortcodes($exc); $exc = apply_filters('the_content', $exc); $exc = str_replace(']]>', ']]&gt;', $exc); $exc = wp_trim_words( $exc, apply_filters('excerpt_length', 55), apply_filters('excerpt_more', ' ' . '[&hellip;]') ); } return apply_filters('wp_trim_excerpt', $exc, $raw); }
Get the post excerpt. Adapted from wp_trim_excerpt() in wp-includes/formatting.php. @param string|null $content Optional. Base content to use for excerpt if post excerpt isn't defined. Defaults to post content @return string
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Post/Model/AbstractPost.php#L246-L263
3ev/wordpress-core
src/Tev/Post/Model/AbstractPost.php
AbstractPost.getFeaturedImage
public function getFeaturedImage() { if ($this->featuredImage === null) { if ($imgId = get_post_thumbnail_id((int) $this->getId())) { $this->featuredImage = $this->postFactory->create(get_post($imgId)); } else { $this->featuredImage = false; } } return $this->featuredImage; }
php
public function getFeaturedImage() { if ($this->featuredImage === null) { if ($imgId = get_post_thumbnail_id((int) $this->getId())) { $this->featuredImage = $this->postFactory->create(get_post($imgId)); } else { $this->featuredImage = false; } } return $this->featuredImage; }
Get this Post's featured image. @return \Tev\Post\Model\Attachment|false Featured image object, or false if not set
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Post/Model/AbstractPost.php#L282-L293
3ev/wordpress-core
src/Tev/Post/Model/AbstractPost.php
AbstractPost.getAuthor
public function getAuthor() { if ($this->author === null) { $this->author = $this->authorFactory->create($this->getAuthorId()); } return $this->author; }
php
public function getAuthor() { if ($this->author === null) { $this->author = $this->authorFactory->create($this->getAuthorId()); } return $this->author; }
Get post author. @return \Tev\Author\Model\Author
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Post/Model/AbstractPost.php#L331-L338
3ev/wordpress-core
src/Tev/Post/Model/AbstractPost.php
AbstractPost.getParent
public function getParent() { if ($this->parent === null) { if (($parentId = $this->getParentPostId()) !== null) { $this->parent = $this->postFactory->create(get_post($parentId)); } else { $this->parent = false; } } return $this->parent ?: null; }
php
public function getParent() { if ($this->parent === null) { if (($parentId = $this->getParentPostId()) !== null) { $this->parent = $this->postFactory->create(get_post($parentId)); } else { $this->parent = false; } } return $this->parent ?: null; }
Get the parent post, if set. @return \Tev\Post\Model\AbstractPost|null
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Post/Model/AbstractPost.php#L355-L366
3ev/wordpress-core
src/Tev/Post/Model/AbstractPost.php
AbstractPost.getTermsFor
public function getTermsFor($taxonomy) { if (!($taxonomy instanceof Taxonomy)) { $taxonomy = $this->taxonomyFactory->create($taxonomy); } return $taxonomy->getTermsForPost($this); }
php
public function getTermsFor($taxonomy) { if (!($taxonomy instanceof Taxonomy)) { $taxonomy = $this->taxonomyFactory->create($taxonomy); } return $taxonomy->getTermsForPost($this); }
Get all terms for this post in the given taxonomy. @param mixed|\Tev\Taxonomy\Model\Taxonomy $taxonomy Taxonomy name or object @return \Tev\Term\Model\Term[] Array of terms
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Post/Model/AbstractPost.php#L442-L449
3ev/wordpress-core
src/Tev/Post/Model/AbstractPost.php
AbstractPost.getPostTypeObject
protected function getPostTypeObject() { if ($this->postTypeObj === null) { $this->postTypeObj = get_post_type_object($this->getType()); } return $this->postTypeObj; }
php
protected function getPostTypeObject() { if ($this->postTypeObj === null) { $this->postTypeObj = get_post_type_object($this->getType()); } return $this->postTypeObj; }
Get the post type object for this post. Contains information about the post type of this post. @return \stdClass
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Post/Model/AbstractPost.php#L494-L501
xiewulong/yii2-wechat
models/WechatNewsItem.php
WechatNewsItem.getArticle
public function getArticle(&$manager = null) { $this->manager = $manager; $article = $this->json; return [ 'index' => $this->index, 'thumb_material_media_id' => $article['thumb_material_media_id'], 'articles' => $article, ]; }
php
public function getArticle(&$manager = null) { $this->manager = $manager; $article = $this->json; return [ 'index' => $this->index, 'thumb_material_media_id' => $article['thumb_material_media_id'], 'articles' => $article, ]; }
获取一条图文素材 @method getArticle @since 0.0.1 @param {object} [&$manager] wechat扩展对象 @return {array} @example $this->getArticles($manager);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/models/WechatNewsItem.php#L32-L42
xiewulong/yii2-wechat
models/WechatNewsItem.php
WechatNewsItem.getJson
public function getJson() { $json = [ 'title' => $this->title, 'author' => $this->author, 'show_cover_pic' => $this->show_cover_pic, 'digest' => $this->digest, 'content_source_url' => $this->content_source_url, ]; if($this->manager) { $materialMedia = $this->thumbMaterialMedia; $json['thumb_media_id'] = $materialMedia->media_id; $json['thumb_material_media_id'] = $materialMedia->id; $json['content'] = $this->wechatContent; } else { $json['thumb_url'] = $this->thumbMaterial->url; $json['content'] = $this->content; } return $json; }
php
public function getJson() { $json = [ 'title' => $this->title, 'author' => $this->author, 'show_cover_pic' => $this->show_cover_pic, 'digest' => $this->digest, 'content_source_url' => $this->content_source_url, ]; if($this->manager) { $materialMedia = $this->thumbMaterialMedia; $json['thumb_media_id'] = $materialMedia->media_id; $json['thumb_material_media_id'] = $materialMedia->id; $json['content'] = $this->wechatContent; } else { $json['thumb_url'] = $this->thumbMaterial->url; $json['content'] = $this->content; } return $json; }
转成接口调用json @method getJson @since 0.0.1 @return {string}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/models/WechatNewsItem.php#L50-L69
xiewulong/yii2-wechat
models/WechatNewsItem.php
WechatNewsItem.getWechatContent
protected function getWechatContent() { $content = $this->content; if(preg_match_all('/<img.*?[\/]?>/i', $content, $imgs)) { $urls = []; foreach($imgs[0] as $img) { if(preg_match_all('/(?<=src|_src|data-src)(?:\s*=\s*")(.*?)(?=")/i', $img, $srcs) && isset($srcs[1]) && $srcs[1]) { $urls = array_merge($urls, $srcs[1]); } } if($urls) { $urls = array_unique($urls); foreach($urls as $url) { $image = WechatNewsImage::findOne($this->manager->addNewsImage($url)); if($image) { $content = str_replace($image->url_source, $image->url, $content); } } } } return $content; }
php
protected function getWechatContent() { $content = $this->content; if(preg_match_all('/<img.*?[\/]?>/i', $content, $imgs)) { $urls = []; foreach($imgs[0] as $img) { if(preg_match_all('/(?<=src|_src|data-src)(?:\s*=\s*")(.*?)(?=")/i', $img, $srcs) && isset($srcs[1]) && $srcs[1]) { $urls = array_merge($urls, $srcs[1]); } } if($urls) { $urls = array_unique($urls); foreach($urls as $url) { $image = WechatNewsImage::findOne($this->manager->addNewsImage($url)); if($image) { $content = str_replace($image->url_source, $image->url, $content); } } } } return $content; }
转换微信格式content @method getWechatContent @since 0.0.1 @return {string} @example $this->getWechatContent();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/models/WechatNewsItem.php#L78-L99
xiewulong/yii2-wechat
models/WechatNewsItem.php
WechatNewsItem.getThumbMaterialMedia
protected function getThumbMaterialMedia() { $media = WechatMaterialMedia::findOne(['appid' => $this->manager->app->appid, 'material_id' => $this->thumb_material_id, 'expired_at' => 0]); if(!$media) { $media = WechatMaterialMedia::findOne($this->manager->addMaterial($this->thumb_material_id)); } return $media; }
php
protected function getThumbMaterialMedia() { $media = WechatMaterialMedia::findOne(['appid' => $this->manager->app->appid, 'material_id' => $this->thumb_material_id, 'expired_at' => 0]); if(!$media) { $media = WechatMaterialMedia::findOne($this->manager->addMaterial($this->thumb_material_id)); } return $media; }
获取缩略图媒体 @method getThumbMaterialMedia @since 0.0.1 @return {object} @example $this->getThumbMaterialMedia();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/models/WechatNewsItem.php#L108-L115