sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function validateDocumentRoot() { // Check that the DOCUMENT_ROOT is a directory called `public`. if (end(explode('\\', $this->documentRoot)) != "public" && end(explode('/', $this->documentRoot)) != "public") { die($this->logEntry("Your servers DOCUMENT_ROOT needs to be a directory called `public`")); } // Check that the DOCUMENT_ROOT parent directory is writable. if (!is_writable(dirname($this->documentRoot))) { die( $this->logEntry( "Web server user does not have access to the DOCUMENT_ROOT's parent directory. ". "This is required in order for Dappur to function properly." ) ); } }
structure is correct
entailment
private function installUpdateComposer() { if (!is_file(dirname($this->documentRoot) . '/composer.phar')) { // Download composer to the DOCUMENT_ROOT's parent directory. if (file_put_contents( dirname($this->documentRoot) . '/composer.phar', fopen("https://getcomposer.org/download/1.7.1/composer.phar", 'r') )) { echo $this->logEntry("Composer downloaded successfully. Making composer.phar executable..."); // CD into DOCUMENT_ROOT parent and make composer.phar executable exec("cd " . dirname($this->documentRoot) . " && chmod +x composer.phar"); } else { echo $this->logEntry("Could not get Composer working. Please check your settings and try again."); } } else { // Check that composer is working $check_composer = shell_exec(dirname($this->documentRoot) . "/composer.phar" . ' --version 2>&1'); echo $this->logEntry($check_composer); if (strpos($check_composer, 'omposer version')) { // Check for Composer updates $update_composer = shell_exec(dirname($this->documentRoot) . "/composer.phar self-update 2>&1"); echo $this->logEntry("Checking For Composer Update..."); echo $this->logEntry($update_composer); } } }
Check if composer is installed or download phar and use that.
entailment
public function setI5Error($errNum, $errCat = I5_CAT_PHP, $errMsg = '', $errDesc = '') { // the array (eventually returned by i5_error() // likes to have both numeric and alphanumeric keys. $i5ErrorArray = array(0=>$errNum, 1=>$errCat, 2=>$errMsg, 3=>$errDesc, 'num'=>$errNum, 'cat'=>$errCat, 'msg'=>$errMsg, 'desc'=>$errDesc); self::$_i5Error = $i5ErrorArray; }
Set error information for last action. @param int $errNum Error number (according to old toolkit). Zero/false if no error @param string $errCat Category of error @param string $errMsg Error message (often a CPF code but sometimes just a message) @param string $errDesc Longer description of error @return void
entailment
public function dtsToYymmdd($dtsDateTime) { $inputFormat = "*DTS"; // special system format, returned by some APIs. $outputFormat = "*YYMD"; // 17 chars long $outputVarname = 'datetimeOut'; $apiPgm = 'QWCCVTDT'; $apiLib = 'QSYS'; $paramXml = "<parm io='in' comment='1. Input format'> <data var='formatIn' type='10A' comment='*DTS is system time stamp format'>$inputFormat</data> </parm> <parm io='in' comment='2. Input variable'> <data var='datetimeIn' type='8b' comment='*DTS format is type 8b (binary)'>$dtsDateTime</data> </parm> <parm io='in' comment='3. Output format'> <data var='formatOut' type='10A' comment='*YYMD means YYYYMMDDHHMMSSmmm (milliseconds)'>$outputFormat</data> </parm> <parm io='out' comment='4. Output variable'> <ds var='$outputVarname' comment='Data structure, total of 17 bytes, to split date/time into YYYYMMDD, HHMMSS, and microseconds, as indicated by *YYMD format'> <data var='date' type='8a' comment='YYYYMMDD' /> <data var='time' type='6a' comment='HHMMSS' /> <data var='microseconds' type='3a' comment='microsecs (3 digits)' /> </ds> </parm>\n" . Toolkit::getErrorDataStructXml(5); // param number 5 // pass param xml directly in. $retPgmArr = $this->ToolkitSrvObj->PgmCall($apiPgm, $apiLib, $paramXml); if ($this->ToolkitSrvObj->getErrorCode()) { return false; } $retArr = $retPgmArr['io_param'][$outputVarname]; return $retArr; }
from 8-character *DTS format to 17-character full date and time @param $dtsDateTime @return bool
entailment
public function blogEdit(Request $request, Response $response, $postId) { //die(var_dump($request->getAttribute('route'))); if ($check = $this->sentinel->hasPerm('blog.update', 'dashboard', $this->config['blog-enabled'])) { return $check; } $post = BlogPosts::where('id', $postId)->with('category')->with('tags')->first(); if (!$post) { $this->flash('danger', 'That post does not exist.'); return $this->redirect($response, 'admin-blog'); } if (!$this->auth->check()->inRole('manager') && !$this->auth->check()->inRole('admin') && $post->user_id != $this->auth->check()->id) { $this->flash('danger', 'You do not have permission to edit that post.'); return $this->redirect($response, 'admin-blog'); } if ($request->isPost()) { if ($this->blogUtils->updatePost($post->id)) { return $this->redirect($this->container->response, 'admin-blog'); } } $currentTags = $post->tags->pluck('id'); return $this->view->render( $response, 'blog-edit.twig', array( "post" => $post->toArray(), "categories" => BlogCategories::get(), "tags" => BlogTags::get(), "currentTags" => $currentTags ) ); }
Edit Blog Post
entailment
public function blogPublish(Request $request, Response $response) { if ($check = $this->sentinel->hasPerm('blog.update', 'dashboard', $this->config['blog-enabled'])) { return $check; } $post = BlogPosts::find($request->getParam('post_id')); if (!$post) { $this->flash('danger', 'That post does not exist.'); return $this->redirect($response, 'admin-blog'); } if (!$this->auth->check()->inRole('manager') && !$this->auth->check()->inRole('admin') && $post->user_id != $this->auth->check()->id) { $this->flash('danger', 'You do not have permission to edit that post.'); return $this->redirect($response, 'admin-blog'); } if ($this->blogUtils->publish()) { $this->flash('success', 'Post was published successfully.'); return $this->redirect($response, 'admin-blog'); } $this->flash('danger', 'There was an error publishing your post.'); return $this->redirect($response, 'admin-blog'); }
Publish Blog Post
entailment
public function setParamProperties($properties = array()) { $map = array('type' => 'type', 'io' => 'io', 'comment' => 'comment', 'var' => 'varName', 'data' => 'data', 'varying' => 'varying', 'dim' => 'dimension', 'by' => 'by', 'array' => 'isArray', 'setlen' => 'labelSetLen', 'len' => 'labelLen', 'dou' => 'labelDoUntil', 'enddo' => 'labelEndDo', 'ccsidBefore' => 'ccsidBefore', 'ccsidAfter' => 'ccsidAfter', 'useHex' => 'useHex', ); // go through all properties and set the ones that are valid, // using the mapping above to find the true property name. foreach ($properties as $key=>$value) { $propName = isset($map[$key]) ? $map[$key] : ''; if ($propName) { // a valid property name was found so set it $this->$propName = $value; } } }
set a parameter's properties via an key=>value array structure. Choose any properties to set. map the XML keywords (usually shorter than true class property names) to the class property names. @param array $properties
entailment
protected function handleParamValue($type, $io, $comment, $varName, $value, $varying, $dimension, $by, $isArray, $labelSetLen, $labelLen, $ccsidBefore, $ccsidAfter, $useHex) { if (is_array($value) && ($type != 'ds')) { $count = count($value); if ($count) { $ds = array(); // make array of parms of the specified type foreach ($value as $key=>$singleValue) { // use $key as a sequential (probably) unique-ifier, though not strictly necessary $ds[] = new self($type, $io, "{$comment}_$key", "{$varName}_$key", $singleValue, $varying, $dimension, $by, $isArray, $labelSetLen, $labelLen, $ccsidBefore, $ccsidAfter, $useHex); } // use the new ds for our value below. $value = $ds; } else { throw new \Exception("Empty array passed as value for {$varName}"); } } return $value; }
if $value is an array, but not yet a data structure, make a data structure of the array elements. @param $type @param $io @param $comment @param $varName @param $value @param $varying @param $dimension @param $by @param $isArray @param $labelSetLen @param $labelLen @param $ccsidBefore @param $ccsidAfter @param $useHex @return array @throws \Exception
entailment
static function bin2str( $hex_data ) { $str=''; $upto = strlen($hex_data); for ($i = 0; $i < $upto; $i+= 2) { $hexPair = $hex_data[$i].$hex_data [$i+1]; /* if hex value starts with 0 (00, 0D, 0A...), * assume it's nondisplayable. * Replace with a space (hex 20) */ if ($hex_data[$i] == '0') { $hexPair = '20'; // space } //(if($hex_data[$i] == '0') ) // break; $str.= chr(hexdec($hexPair)); //$str.= chr(hexdec($hex_data[$i].$hex_data [$i+1])); } return $str; }
bin2str is used by the 5250 Bridge. It converts a hex string to character string while cleaning up unexpected characters. Original comment: "can not be public. Return XML does not return a type of values." @param $hex_data @return string
entailment
public function up() { $this->schema->table('users', function (Blueprint $table) { $table->string('2fa')->after('password')->nullable(); }); // Add 2FA Config Group $config = new \Dappur\Model\ConfigGroups; $config->name = "2FA"; $config->description = "2FA Settings"; $config->save(); $init_config = array( array($config->id, '2fa-enabled', 'Enable 2FA', 6, 0) ); // Seed Config Table foreach ($init_config as $value) { $config = new Dappur\Model\Config; $config->group_id = $value[0]; $config->name = $value[1]; $config->description = $value[2]; $config->type_id = $value[3]; $config->value = $value[4]; $config->save(); } }
Write your reversible migrations using this method. Dappur Framework uses Laravel Eloquent ORM as it's database connector. More information on writing eloquent migrations is available here: https://laravel.com/docs/5.4/migrations Remember to use both the up() and down() functions in order to be able to roll back. Create Table Sample: $this->schema->create('sample', function (Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); $table->string('last_name')->nullable(); $table->string('first_name')->nullable(); $table->timestamps(); }); Drop Table Sample: $this->schema->dropIfExists('sample');
entailment
public function receiveDataQueue($WaitTime, $KeyOrder = '', $KeyLength = 0, $KeyData = '', $WithRemoveMsg = 'N') { // call misspelled one return $this->receieveDataQueue($WaitTime, $KeyOrder, $KeyLength, $KeyData, $WithRemoveMsg); }
Correct spelling with this alias @param $WaitTime @param string $KeyOrder @param int $KeyLength @param string $KeyData @param string $WithRemoveMsg @return bool
entailment
public function GetSPLF($SplfName , $SplfNbr, $JobNmbr, $JobName, $JobUser, $TMPFName='') { $this->clearError(); if ($TMPFName != '') { $this->TMPFName = $TMPFName; } // @todo under the flag for current Object??? $crtf = "CRTDUPOBJ OBJ(ZSF255) FROMLIB(" . $this->ToolkitSrvObj->getOption('HelperLib') . ") OBJTYPE(*FILE) TOLIB($this->TmpLib) NEWOBJ($this->TMPFName)"; $this->ToolkitSrvObj->ClCommandWithCpf($crtf); // was ClCommand // clear the temp file $clrpfm = "CLRPFM $this->TmpLib/$this->TMPFName"; $this->ToolkitSrvObj->ClCommandWithCpf($clrpfm); // these all were CLCommand but we need CPFs. // copy spooled file to temp file $cmd = sprintf ("CPYSPLF FILE(%s) TOFILE($this->TmpLib/$this->TMPFName) JOB(%s/%s/%s) SPLNBR(%s)", $SplfName, trim($JobNmbr), trim($JobUser), trim($JobName), $SplfNbr); $this->ToolkitSrvObj->ClCommandWithCpf($cmd); sleep(1); // read the data from temp file $Txt = $this->ReadSPLFData(); // delete temp file $dltf = "DLTF FILE($this->TmpLib/$this->TMPFName)"; $this->ToolkitSrvObj->ClCommandWithCpf($dltf); return $Txt; }
multi user using! @param $SplfName @param $SplfNbr @param $JobNmbr @param $JobName @param $JobUser @param string $TMPFName @return mixed|string
entailment
protected function setStmtError($stmt = null) { if ($stmt) { $this->setErrorCode(db2_stmt_error($stmt)); $this->setErrorMsg(db2_stmt_errormsg($stmt)); } else { $this->setErrorCode(db2_stmt_error()); $this->setErrorMsg(db2_stmt_errormsg()); } }
set error code and message based on last db2 prepare or execute error. @todo: consider using GET DIAGNOSTICS for even more message text: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Frzala%2Frzalafinder.htm @param null $stmt
entailment
public function execXMLStoredProcedure($conn, $sql, $bindArray) { $internalKey = $bindArray['internalKey']; $controlKey = $bindArray['controlKey']; $inputXml = $bindArray['inputXml']; $outputXml = $bindArray['outputXml']; // @todo see why error doesn't properly bubble up to top level. $crsr = @db2_prepare($conn, $sql); if (!$crsr) { $this->setStmtError(); return false; } // stored procedure takes four parameters. Each 'name' will be bound to a real PHP variable $params = array( array('position' => 1, 'name' => "internalKey", 'inout' => DB2_PARAM_IN), array('position' => 2, 'name' => "controlKey", 'inout' => DB2_PARAM_IN), array('position' => 3, 'name' => "inputXml", 'inout' => DB2_PARAM_IN), array('position' => 4, 'name' => "outputXml", 'inout' => DB2_PARAM_OUT), ); // bind the four parameters foreach ($params as $param) { $ret = db2_bind_param ($crsr, $param['position'], $param['name'], $param['inout']); if (!$ret) { // unable to bind a param. Set error and exit $this->setStmtError($crsr); return false; } } $ret = @db2_execute($crsr); if (!$ret) { // execution of XMLSERVICE stored procedure failed. $this->setStmtError($crsr); return false; } return $outputXml; }
this function used for special stored procedure call only @param $conn @param $sql @return bool
entailment
public function executeQuery($conn, $sql) { $txt = array(); $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE)); if (is_resource($stmt)) { if (db2_fetch_row($stmt)) { $column = db2_result($stmt, 0); $txt[] = $column; } } else { $this->setStmtError(); Throw new \Exception("Failure executing SQL: ($sql) " . db2_stmt_errormsg(), db2_stmt_error()); } return $txt; }
returns a first column from sql stmt result set used in one place: iToolkitService's ReadSPLFData(). @todo eliminate this method if possible. @param $conn @param $sql @throws \Exception @return array
entailment
public function getSystemValue($sysValueName) { if (!$this->ToolkitSrvObj instanceof Toolkit) { return false; } $Err = ' '; $SysValue = ' '; $params [] = $this->ToolkitSrvObj->AddParameterChar('both', 1, "ErrorCode", 'errorcode', $Err); $params [] = $this->ToolkitSrvObj->AddParameterChar('both', 10, "SysValName", 'sysvalname', $sysValueName); $params [] = $this->ToolkitSrvObj->AddParameterChar('both', 1024, "SysValue", 'sysval', $SysValue); $retArr = $this->ToolkitSrvObj->PgmCall(ZSTOOLKITPGM, $this->ToolkitSrvObj->getOption('HelperLib'), $params, NULL, array('func' => 'RTVSYSVAL')); if ($retArr !== false && isset($retArr['io_param'])) { $sysval = $retArr['io_param']; if (isset($sysval['sysvalname'])) { return $sysval['sysval']; } else { $this->setError($sysval['errorcode']); } } }
@todo QWCRSVAL to work with 2 tiers while retaining good performance @param $sysValueName
entailment
public function up() { $this->schema->create('routes', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('pattern')->unique(); $table->text('content')->nullable(); $table->text('css')->nullable(); $table->text('js')->nullable(); $table->string('permission')->nullable(); $table->boolean('status')->default(0); $table->timestamps(); }); $this->schema->create('role_routes', function (Blueprint $table) { $table->increments('id'); $table->integer('role_id')->unsigned(); $table->integer('route_id')->unsigned(); $table->timestamps(); $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade'); $table->foreign('route_id')->references('id')->on('routes')->onDelete('cascade'); }); // Insert Home Page $ins = new \Dappur\Model\Routes; $ins->name = "home"; $ins->pattern = ""; $ins->content = '<div class="container"><div class="jumbotron"><div class="row"><div class="col-md-12" style="text-align: right;">{% if auth.user() %}Welcome, {{auth.user.first_name}} {{ auth.user.last_name }}!{% endif %}</div></div><div class="row"><div class="col-md-12"><p>Bacon ipsum dolor amet bresaola turkey spare ribs, shank shoulder salami short loin pig meatball doner frankfurter pork buffalo. Leberkas tongue jerky venison alcatra. Ribeye picanha shank turkey strip steak frankfurter pork belly doner leberkas alcatra meatball. Leberkas biltong shankle cow hamburger, strip steak beef turkey bresaola buffalo meatball prosciutto pancetta capicola.</p><p>Drumstick kielbasa kevin ribeye beef ribs pork chop. Turducken shoulder alcatra picanha frankfurter ball tip buffalo venison cow flank. Meatloaf picanha prosciutto frankfurter cow, shoulder tongue ham hock pancetta shankle flank kielbasa porchetta. Turducken shankle beef ribs swine cupim frankfurter alcatra venison turkey fatback pork doner.</p><p>Corned beef shankle porchetta, pig shoulder strip steak turducken doner frankfurter prosciutto ham hock salami. Landjaeger kevin shankle biltong ham hock. Ground round short loin pig, andouille ribeye drumstick brisket filet mignon doner picanha bresaola tongue rump jerky fatback. Buffalo shank landjaeger tongue. Boudin corned beef jerky, sausage bresaola short ribs pork loin rump t-bone. Sausage turkey bresaola ham hock hamburger chicken tenderloin capicola meatball.</p><p>Brisket burgdoggen pork chop landjaeger t-bone buffalo picanha ham hock frankfurter boudin kevin meatball biltong tongue pancetta. Tenderloin salami ribeye, meatloaf brisket strip steak corned beef drumstick. Cupim meatball flank pastrami bresaola. Pancetta sausage corned beef doner filet mignon, prosciutto meatball boudin beef ribs. Beef ribs tenderloin chuck, kielbasa pork loin t-bone andouille pork chop short loin capicola spare ribs. Picanha pork belly drumstick porchetta, chuck hamburger strip steak pork buffalo pancetta salami ball tip frankfurter shank bacon. Tongue jowl ham hock, filet mignon ham hamburger beef biltong pork belly.</p><p>Cupim drumstick salami andouille. Kielbasa buffalo venison pastrami, bresaola strip steak beef ribs jowl. Sirloin pork belly burgdoggen doner tri-tip, brisket bresaola turkey short ribs picanha. Beef drumstick tenderloin, shoulder short ribs buffalo turkey. Tongue short ribs capicola venison. Venison meatball tail kevin bacon, hamburger cow doner pastrami shankle. Brisket shank cupim, tongue tri-tip ball tip picanha pig.</p></div></div></div></div>'; $ins->status = 1; $ins->save(); // Insert Privacy $ins = new \Dappur\Model\Routes; $ins->name = "privacy"; $ins->pattern = "privacy"; $ins->content = '<div class="container"> <div class="jumbotron"> <div class="row text-center"> <div class="col-md-4 col-md-offset-4"> <p style="font-size: 14px;"> <img src="{{config[\'logo\']}}" class="img-responsive" alt="{{ config[\'site-name\'] }} Logo"> </p> </div> </div> <div class="row"> <div class="col-md-12"> <h2>Privacy Policy</h2><p style="font-size: 14px;">{{ config[\'site-name\'] }} operates the {{ config[\'domain\'] }} website, which provides the {{config[\'privacy-service\']}}.</p><p style="font-size: 14px;">This page is used to inform website visitors regarding our policies with the collection, use, and disclosure of Personal Information if anyone decided to use our Service.</p><p style="font-size: 14px;">If you choose to use our Service, then you agree to the collection and use of information in relation with this policy. The Personal Information that we collect are used for providing and improving the Service. We will not use or share your information with anyone except as described in this Privacy Policy.</p><p style="font-size: 14px;">The terms used in this Privacy Policy have the same meanings as in our Terms and Conditions, which is accessible at {{ config[\'site-domain\'] }} , unless otherwise defined in this Privacy Policy.</p><h4>Information Collection and Use</h4><p style="font-size: 14px;">For a better experience while using our Service, we may require you to provide us with certain personally identifiable information, including but not limited to your name, phone number, and postal address. The information that we collect will be used to contact or identify you.</p><h4>Log Data</h4><p style="font-size: 14px;">We want to inform you that whenever you visit our Service, we collect information that your browser sends to us that is called Log Data. This Log Data may include information such as your computer’s Internet Protocol (“IP”) address, browser version, pages of our Service that you visit, the time and date of your visit, the time spent on those pages, and other statistics.</p><h4>Cookies</h4><p style="font-size: 14px;">Cookies are files with small amount of data that is commonly used an anonymous unique identifier. These are sent to your browser from the website that you visit and are stored on your computer’s hard drive.</p><p style="font-size: 14px;">Our website uses these “cookies” to collection information and to improve our Service. You have the option to either accept or refuse these cookies, and know when a cookie is being sent to your computer. If you choose to refuse our cookies, you may not be able to use some portions of our Service.</p><h4>Service Providers</h4><p style="font-size: 14px;">We may employ third-party companies and individuals due to the following reasons:</p><p style="font-size: 14px;"><ul><li>To facilitate our Service;</li><li>To provide the Service on our behalf;</li><li>To perform Service-related services; or</li><li>To assist us in analyzing how our Service is used.</li><li>We want to inform our Service users that these third parties have access to your Personal Information. The reason is to perform the tasks assigned to them on our behalf. However, they are obligated not to disclose or use the information for any other purpose.</li></ul></p><h4>Security</h4><p style="font-size: 14px;">We value your trust in providing us your Personal Information, thus we are striving to use commercially acceptable means of protecting it. But remember that no method of transmission over the internet, or method of electronic storage is 100% secure and reliable, and we cannot guarantee its absolute security.</p><h4>Links to Other Sites</h4><p style="font-size: 14px;">Our Service may contain links to other sites. If you click on a third-party link, you will be directed to that site. Note that these external sites are not operated by us. Therefore, we strongly advise you to review the Privacy Policy of these websites, more helpful hints. We have no control over, and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services.</p><h4>Children’s Privacy</h4><p style="font-size: 14px;">Our Services do not address anyone under the age of 13. We do not knowingly collect personal identifiable information from children under 13. In the case we discover that a child under 13 has provided us with personal information, we immediately delete this from our servers. If you are a parent or guardian and you are aware that your child has provided us with personal information, please contact us so that we will be able to do necessary actions.</p><h4>Changes to This Privacy Policy</h4><p style="font-size: 14px;">We may update our Privacy Policy from time to time. Thus, we advise you to review this page periodically for any changes. We will notify you of any changes by posting the new Privacy Policy on this page. These changes are effective immediately, after they are posted on this page.</p><h4>Contact Us</h4><p style="font-size: 14px;">If you have any questions or suggestions about our Privacy Policy, do not hesitate to contact us.</p><p style="font-size: 14px;">This Privacy Policy page was created at privacypolicytemplate.net.</p> </div> </div> </div></div>'; $ins->status = 1; $ins->save(); // Insert Terms $ins = new \Dappur\Model\Routes; $ins->name = "terms"; $ins->pattern = "terms"; $ins->content = '<div class="container"> <div class="jumbotron"> <div class="row text-center"> <div class="col-md-4 col-md-offset-4"> <p style="font-size: 14px;"> <img src="{{config[\'logo\']}}" class="img-responsive" alt="{{ config[\'site-name\'] }} Logo"> </p> </div> </div> <div class="row"> <div class="col-md-12"> <h2>Terms &amp; Conditions</h2><p style="font-size: 14px;">These terms and conditions outline the rules and regulations for the use of <b>{{ config[\'site-name\'] }}</b>\'s Website.</p><p style="font-size: 14px;"><b>{{ config[\'site-name\'] }}</b> is located at:<br/>{{ config[\'contact-street\'] }}<br/>{{ config[\'contact-city\'] }}, {{ config[\'contact-state\'] }} {{ config[\'contact-zip\'] }}<br />{{ config[\'contact-country\'] }}</p><p style="font-size: 14px;">By accessing this website we assume you accept these terms and conditions in full. Do not continue to use <b>{{ config[\'site-name\'] }}</b>\'s website if you do not accept all of the terms and conditions stated on this page.</p><p style="font-size: 14px;">The following terminology applies to these Terms and Conditions, Privacy Statement and Disclaimer Notice and any or all Agreements: “Client”, “You” and “Your” refers to you, the person accessing this website and accepting the Company’s terms and conditions. “The Company”, “Ourselves”, “We”, “Our” and “Us”, refers to our Company. “Party”, “Parties”, or “Us”, refers to both the Client and ourselves, or either the Client or ourselves. All terms refer to the offer, acceptance and consideration of payment necessary to undertake the process of our assistance to the Client in the most appropriate manner, whether by formal meetings of a fixed duration, or any other means, for the express purpose of meeting the Client’s needs in respect of provision of the Company’s stated services/products, in accordance with and subject to, prevailing law of {{ config[\'contact-country\'] }}. Any use of the above terminology or other words in the singular, plural, capitalisation and/or he/she or they, are taken as interchangeable and therefore as referring to same.</p><h4>Cookies</h4><p style="font-size: 14px;">We employ the use of cookies. By using <b>{{ config[\'site-name\'] }}</b>\'s website you consent to the use of cookies in accordance with <b>{{ config[\'site-name\'] }}</b>’s privacy policy.</p><p style="font-size: 14px;">Most of the modern day interactive web sites use cookies to enable us to retrieve user details for each visit. Cookies are used in some areas of our site to enable the functionality of this area and ease of use for those people visiting. Some of our affiliate / advertising partners may also use cookies.</p><h4>License</h4><p style="font-size: 14px;">Unless otherwise stated, <b>{{ config[\'site-name\'] }}</b> and/or it’s licensors own the intellectual property rights for all material on <b>{{ config[\'site-name\'] }}</b>. All intellectual property rights are reserved. You may view and/or print pages from {{ config[\'domain\'] }} for your own personal use subject to restrictions set in these terms and conditions.</p><p style="font-size: 14px;">You must not:</p><ol><li>Republish material from {{ config[\'domain\'] }}</li><li>Sell, rent or sub-license material from {{ config[\'domain\'] }}</li><li>Reproduce, duplicate or copy material from {{ config[\'domain\'] }}</li></ol><p style="font-size: 14px;">Redistribute content from <b>{{ config[\'site-name\'] }}</b> (unless content is specifically made for redistribution).</p><h4>User Comments</h4><ol><li>This Agreement shall begin on the date hereof.</li><li>Certain parts of this website offer the opportunity for users to post and exchange opinions, information, material and data (\'Comments\') in areas of the website. <b>{{ config[\'site-name\'] }}</b> does not screen, edit, publish or review Comments prior to their appearance on the website and Comments do not reflect the views or opinions of<b>{{ config[\'site-name\'] }}</b>, its agents or affiliates. Comments reflect the view and opinion of the person who posts such view or opinion. To the extent permitted by applicable laws <b>{{ config[\'site-name\'] }}</b>shall not be responsible or liable for the Comments or for any loss cost, liability, damages or expenses caused and or suffered as a result of any use of and/or posting of and/or appearance of the Comments on this website.</li><li><b>{{ config[\'site-name\'] }}</b>reserves the right to monitor all Comments and to remove any Comments which it considers in its absolute discretion to be inappropriate, offensive or otherwise in breach of these Terms and Conditions.</li><li>You warrant and represent that:<ol><li>You are entitled to post the Comments on our website and have all necessary licenses and consents to do so;</li><li>The Comments do not infringe any intellectual property right, including without limitation copyright, patent or trademark, or other proprietary right of any third party;</li><li>The Comments do not contain any defamatory, libelous, offensive, indecent or otherwise unlawful material or material which is an invasion of privacy</li><li>The Comments will not be used to solicit or promote business or custom or present commercial activities or unlawful activity.</li></ol></li><li>You hereby grant to <strong><b>{{ config[\'site-name\'] }}</b></strong> a non-exclusive royalty-free license to use, reproduce, edit and authorize others to use, reproduce and edit any of your Comments in any and all forms, formats or media.</li></ol><h4>Hyperlinking to our Content</h4><ol><li>The following organizations may link to our Web site without prior written approval:<ol><li>Government agencies;</li><li>Search engines;</li><li>News organizations;</li><li>Online directory distributors when they list us in the directory may link to our Web site in the same manner as they hyperlink to the Web sites of other listed businesses; and</li><li>Systemwide Accredited Businesses except soliciting non-profit organizations, charity shopping malls, and charity fundraising groups which may not hyperlink to our Web site.</li></ol></li></ol><ol start="2"><li>These organizations may link to our home page, to publications or to other Web site information so long as the link: (a) is not in any way misleading; (b) does not falsely imply sponsorship, endorsement or approval of the linking party and its products or services; and (c) fits within the context of the linking party\'s site.</li><li>We may consider and approve in our sole discretion other link requests from the following types of organizations:<ol><li>commonly-known consumer and/or business information sources such as Chambers of Commerce, American Automobile Association, AARP and Consumers Union;</li><li>dot.com community sites;</li><li>associations or other groups representing charities, including charity giving sites,</li><li>online directory distributors;</li><li>internet portals;</li><li>accounting, law and consulting firms whose primary clients are businesses; and</li><li>educational institutions and trade associations.</li></ol></li></ol><p style="font-size: 14px;">We will approve link requests from these organizations if we determine that: (a) the link would not reflect unfavorably on us or our accredited businesses (for example, trade associations or other organizations representing inherently suspect types of business, such as work-at-home opportunities, shall not be allowed to link); (b)the organization does not have an unsatisfactory record with us; (c) the benefit to us from the visibility associated with the hyperlink outweighs the absence of <?=$companyName?>; and (d) where the link is in the context of general resource information or is otherwise consistent with editorial content in a newsletter or similar product furthering the mission of the organization.</p><p style="font-size: 14px;">These organizations may link to our home page, to publications or to other Web site information so long as the link: (a) is not in any way misleading; (b) does not falsely imply sponsorship, endorsement or approval of the linking party and it products or services; and (c) fits within the context of the linking party\'s site.</p><p style="font-size: 14px;">If you are among the organizations listed in paragraph 2 above and are interested in linking to our website, you must notify us by sending an e-mail to <a href="mailto:{{config[\'contact-email\']}}" title="send an email to {{config[\'contact-email\']}}">{{config[\'contact-email\']}}</a>. Please include your name, your organization name, contact information (such as a phone number and/or e-mail address) as well as the URL of your site, a list of any URLs from which you intend to link to our Web site, and a list of the URL(s) on our site to which you would like to link. Allow 2-3 weeks for a response.</p><p style="font-size: 14px;">Approved organizations may hyperlink to our Web site as follows:</p><ol><li>By use of our corporate name; or</li><li>By use of the uniform resource locator (Web address) being linked to; or</li><li>By use of any other description of our Web site or material being linked to that makes sense within the context and format of content on the linking party\'s site.</li></ol><p style="font-size: 14px;">No use of <b>{{ config[\'site-name\'] }}</b>’s logo or other artwork will be allowed for linking absent a trademark license agreement.</p><h4>Iframes</h4><p style="font-size: 14px;">Without prior approval and express written permission, you may not create frames around our Web pages or use other techniques that alter in any way the visual presentation or appearance of our Web site.</p><h4>Reservation of Rights</h4><p style="font-size: 14px;">We reserve the right at any time and in its sole discretion to request that you remove all links or any particular link to our Web site. You agree to immediately remove all links to our Web site upon such request. We also reserve the right to amend these terms and conditions and its linking policy at any time. By continuing to link to our Web site, you agree to be bound to and abide by these linking terms and conditions.</p><h4>Removal of links from our website</h4><p style="font-size: 14px;">If you find any link on our Web site or any linked web site objectionable for any reason, you may contact us about this. We will consider requests to remove links but will have no obligation to do so or to respond directly to you.</p><p style="font-size: 14px;">Whilst we endeavour to ensure that the information on this website is correct, we do not warrant its completeness or accuracy; nor do we commit to ensuring that the website remains available or that the material on the website is kept up to date.</p><h4>Content Liability</h4><p style="font-size: 14px;">We shall have no responsibility or liability for any content appearing on your Web site. You agree to indemnify and defend us against all claims arising out of or based upon your Website. No link(s) may appear on any page on your Web site or within any context containing content or materials that may be interpreted as libelous, obscene or criminal, or which infringes, otherwise violates, or advocates the infringement or other violation of, any third party rights.</p><h4>Disclaimer</h4><p style="font-size: 14px;">To the maximum extent permitted by applicable law, we exclude all representations, warranties and conditions relating to our website and the use of this website (including, without limitation, any warranties implied by law in respect of satisfactory quality, fitness for purpose and/or the use of reasonable care and skill). Nothing in this disclaimer will:</p><ol><li>limit or exclude our or your liability for death or personal injury resulting from negligence;</li><li>limit or exclude our or your liability for fraud or fraudulent misrepresentation;</li><li>limit any of our or your liabilities in any way that is not permitted under applicable law; or</li><li>exclude any of our or your liabilities that may not be excluded under applicable law.</li></ol><p style="font-size: 14px;">The limitations and exclusions of liability set out in this Section and elsewhere in this disclaimer: (a) are subject to the preceding paragraph; and (b) govern all liabilities arising under the disclaimer or in relation to the subject matter of this disclaimer, including liabilities arising in contract, in tort (including negligence) and for breach of statutory duty.</p><p style="font-size: 14px;">To the extent that the website and the information and services on the website are provided free of charge, we will not be liable for any loss or damage of any nature.</p><h4></h4><p style="font-size: 14px;"></p><h2>Credit &amp; Contact Information</h2><p style="font-size: 14px;">This Terms and conditions page was created at <a href="https://termsandconditionstemplate.com">termsandconditionstemplate.com</a> generator. If you have any queries regarding any of our terms, please contact us.</p> </div> </div> </div></div>'; $ins->status = 1; $ins->save(); // Update Admin Role $admin_role = $this->sentinel->findRoleByName('Admin'); $admin_role->addPermission('pages.*'); $admin_role->save(); }
Write your reversible migrations using this method. Dappur Framework uses Laravel Eloquent ORM as it's database connector. More information on writing eloquent migrations is available here: https://laravel.com/docs/5.4/migrations Remember to use both the up() and down() functions in order to be able to roll back. Create Table Sample: $this->schema->create('sample', function (Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); $table->string('last_name')->nullable(); $table->string('first_name')->nullable(); $table->timestamps(); }); Drop Table Sample: $this->schema->dropIfExists('sample');
entailment
public function getNextEntry() { $apiPgm = 'QGYGTLE'; $apiLib = 'QSYS'; $receiverDs = $this->_receiverDs; $requestHandle = $this->_requestHandle; $lengthOfReceiverVariable = $this->_receiverSize; $nextRecordToRequest = $this->_nextRecordToRequest++; // assign to me, then increment for next time $outputVarname = 'receiver'; $lenLabel= 'size' . $outputVarname; $paramXml = "<parm io='out' comment='1. receiver data'> <ds var='$outputVarname' comment='receiver appropriate to whatever API created the list' len='$lenLabel'> $receiverDs </ds> </parm> <parm io='both' comment='2. Length of receiver variable'> <data var='receiverLen' type='10i0' setlenx='$lenLabel'>$lengthOfReceiverVariable</data> </parm> <parm io='in' comment='3. Request handle'> <data var='requestHandle' comment='Request handle: binary/hex' type='4b'>$requestHandle</data> </parm>\n" . $this->ToolkitSrvObj->getListInfoApiXml(4) . "\n" . "<parm io='in' comment='5. Number of records to return'> <data var='numRecsDesired' type='10i0'>1</data> </parm> <parm io='in' comment='6. Starting record' > <data var='startingRecordNum' comment='First entry number to put in receiver var. If getting one record at a time, increment this each time.' type='10i0'>$nextRecordToRequest</data> </parm>\n" . Toolkit::getErrorDataStructXmlWithCode(7); // param number 7 // was getErrorDataStructXml // pass param xml directly in. $retPgmArr = $this->ToolkitSrvObj->PgmCall($apiPgm, $apiLib, $paramXml); if ($this->ToolkitSrvObj->getErrorCode()) { return false; } /* Even when no error reported by XMLSERVICE (->error), * we may get a GUI0006 in DS error structure exeption code, since we * supplied a full error data structure above (getErrorDataStructXmlWithCode). */ $apiErrCode = $retPgmArr['io_param']['errorDs']['exceptId']; if ($apiErrCode != '0000000') { // Note: caller can check for GUI0006 and GUI0001 (expected when go past last record) vs. any other error (not expected) $this->ToolkitSrvObj->setErrorCode($apiErrCode); return false; } $retArr = $retPgmArr['io_param'][$outputVarname]; return $retArr; }
Call QGYGTLE (get list entry) API using handle and "next record to request." Note: if get timing problems where no records are returned: Embed the call to the QGYGTLE API in a do-loop that loops until a record is returned. @return bool Return false when run out of records (get GUI0006 error code).
entailment
public function close() { // call QGYCLST, the "close list" api. $apiPgm = 'QGYCLST'; $apiLib = 'QSYS'; $requestHandle = $this->_requestHandle; $paramXml = "<parm io='in' comment='1. request handle'> <data var='requestHandle' comment='Request handle: binary/hex' type='4b'>$requestHandle</data> </parm>\n" . Toolkit::getErrorDataStructXml(2); // param number 2 // pass param xml directly in. $this->ToolkitSrvObj->PgmCall($apiPgm, $apiLib, $paramXml); // GUI0006 means end of list if ($this->ToolkitSrvObj->getErrorCode()) { return false; } else { return true; } }
close the list @return bool
entailment
static function getInstance($databaseNameOrResource = '*LOCAL', $userOrI5NamingFlag = '', $password = '', $extensionPrefix = '', $isPersistent = false, $forceNew = false) { // if we're forcing a new instance, close db conn first if exists. if ($forceNew && self::hasInstance() && isset(self::$instance->conn)) { self::$instance->disconnect(); } // if we're forcing a new instance, or an instance hasn't been created yet, create one if ($forceNew || self::$instance == NULL) { $toolkitService = __CLASS__; self::$instance = new $toolkitService($databaseNameOrResource, $userOrI5NamingFlag, $password, $extensionPrefix, $isPersistent); } if (self::$instance) { // instance exists return self::$instance; } else { // some problem return false; } }
need to define this so we get Cw object and not parent object @param string $databaseNameOrResource @param string $userOrI5NamingFlag @param string $password @param string $extensionPrefix @param bool $isPersistent @param bool $forceNew @return bool|null
entailment
public function setOutputVarsToExport(array $outputDesc, array $outputValues) { // for each piece of output, export it according to var name given in $outputDesc. if ($outputValues && is_array($outputValues) && count($outputValues)) { // initialize $this->_outputVarsToExport = array(); foreach ($outputValues as $paramName=>$value) { if (isset($outputDesc[$paramName])) { $variableNameToExport = $outputDesc[$paramName]; // create the global variable named by $ varName. $GLOBALS[$variableNameToExport] = $value; $this->_outputVarsToExport[$variableNameToExport] = $value; } } } return true; }
After calling a program or command, we can export output as variables. This method creates an array that can later be extracted into variables. param array $outputDesc Format of output params 'CODE'=>'CODEvar' where the value becomes a PHP var name param array $outputValues Optional. Array of output values to export @param array $outputDesc @param array $outputValues @return boolean true on success, false on some error
entailment
public function up() { $this->schema->table('routes', function (Blueprint $table) { $table->boolean('sidebar')->after('js')->default(0); $table->boolean('header')->after('sidebar')->default(0); $table->text('header_text')->after('header')->nullable(); $table->string('header_image')->after('header_text')->nullable(); }); }
Write your reversible migrations using this method. Dappur Framework uses Laravel Eloquent ORM as it's database connector. More information on writing eloquent migrations is available here: https://laravel.com/docs/5.4/migrations Remember to use both the up() and down() functions in order to be able to roll back. Create Table Sample: $this->schema->create('sample', function (Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); $table->string('last_name')->nullable(); $table->string('first_name')->nullable(); $table->timestamps(); }); Drop Table Sample: $this->schema->dropIfExists('sample');
entailment
public function up() { $this->schema->create('menus', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->json('json')->nullable(); $table->timestamps(); }); $ins = new \Dappur\Model\Menus; $ins->id = 1; $ins->name = "Dappur Menu"; $ins->json = '[{"text":"Home","href":"","icon":"fa fa-home","target":"_self","title":"","auth":"false","page":"home","guest":"false","roles":[],"active":["home"],"classes":[],"html_id":"","tooltip":"","permission":""},{"text":"Blog","href":"","icon":"fa fa-eye","target":"_self","title":"","auth":"false","page":"blog","guest":"false","roles":[],"active":["blog","blog-author","blog-category","blog-post","blog-tag"],"classes":[],"html_id":"","tooltip":"","permission":"","config_boolean":"blog-enabled"},{"text":"Contact","href":"","icon":"fa fa-phone","target":"_self","title":"","auth":"false","page":"contact","guest":"false","roles":[],"active":["contact"],"classes":[],"html_id":"","tooltip":"","permission":""},{"text":"Login","href":"","icon":"fa fa-lock","target":"_self","title":"","auth":"false","page":"login","guest":"true","roles":[],"active":["activate","forgot-password","login"],"classes":[],"html_id":"","tooltip":"","permission":""},{"text":"Register","href":"","icon":"fa fa-user-circle-o","target":"_self","title":"","auth":"false","page":"register","guest":"true","roles":[],"active":["register"],"classes":[],"html_id":"","tooltip":"","permission":""},{"text":"{{user.username}}","href":"","icon":"fa fa-user-circle-o","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":["profile"],"classes":[],"html_id":"","tooltip":"","permission":"","children":[{"text":"Admin Dashboard","href":"","icon":"fa fa-dashboard","target":"_self","title":"","auth":"true","page":"dashboard","guest":"false","roles":[],"active":["dashboard"],"classes":[],"html_id":"","tooltip":"","permission":"dashboard.*"},{"text":"Profile","href":"","icon":"fa fa-clipboard","target":"_self","title":"","auth":"true","page":"profile","guest":"false","roles":[],"active":["profile","profile-incomplete"],"classes":[],"html_id":"","tooltip":"","permission":""},{"text":"Logout","href":"","icon":"fa fa-lock","target":"_self","title":"","auth":"true","page":"logout","guest":"false","roles":[],"active":[],"classes":[],"html_id":"","tooltip":"","permission":""}]}]'; $ins->save(); $ins = new \Dappur\Model\Menus; $ins->id = 2; $ins->name = "AdminLTE Sidebar"; $ins->json = '[{"text":"Dashboard","href":"","icon":"fa fa-dashboard","target":"_self","title":"","auth":"true","page":"dashboard","guest":"false","roles":[],"active":["dashboard"],"classes":[],"html_id":"","tooltip":"","permission":"dashbaord.view"},{"text":"Users","href":"","icon":"fa fa-users","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":["admin-roles-add","admin-roles-edit","admin-users","admin-users-add","admin-users-edit"],"classes":[],"html_id":"","tooltip":"","permission":"user.view","children":[{"text":"All Users","href":"","icon":"fa fa-users","target":"_self","title":"","auth":"true","page":"admin-users","guest":"false","roles":[],"active":["admin-roles-add","admin-roles-edit","admin-users","admin-users-edit"],"classes":[],"html_id":"","tooltip":"","permission":"user.view"},{"text":"New User","href":"","icon":"fa fa-plus","target":"_self","title":"","auth":"false","page":"admin-users-add","guest":"false","roles":[],"active":["admin-users-add"],"classes":[],"html_id":"","tooltip":"","permission":"user.create"}]},{"text":"Emails","href":"","icon":"fa fa-envelope","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":["admin-email","admin-email-details","admin-email-new","admin-email-template","admin-email-template-add","admin-email-template-edit"],"classes":[],"html_id":"","tooltip":"","permission":"email.view","children":[{"text":"Sent Emails","href":"","icon":"fa fa-envelope-open","target":"_self","title":"","auth":"true","page":"admin-email","guest":"false","roles":[],"active":["admin-email","admin-email-details"],"classes":[],"html_id":"","tooltip":"","permission":"email.view"},{"text":"New Email","href":"","icon":"fa fa-send","target":"_self","title":"","auth":"true","page":"admin-email-new","guest":"false","roles":[],"active":["admin-email-new"],"classes":[],"html_id":"","tooltip":"","permission":"email.create"},{"text":"Templates","href":"","icon":"fa fa-envelope-square","target":"_self","title":"","auth":"false","page":"admin-email-template","guest":"false","roles":[],"active":["admin-email-template","admin-email-template-edit"],"classes":[],"html_id":"","tooltip":"","permission":"email.view"},{"text":"New Template","href":"","icon":"fa fa-plus","target":"_self","title":"","auth":"true","page":"admin-email-template-add","guest":"false","roles":[],"active":["admin-email-template-add"],"classes":[],"html_id":"","tooltip":"","permission":"email.create"}]},{"text":"Blog","href":"","icon":"fa fa-newspaper-o","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":["admin-blog","admin-blog-add","admin-blog-categories-edit","admin-blog-comment-details","admin-blog-comments","admin-blog-edit","admin-blog-preview","admin-blog-tags-edit"],"classes":[],"html_id":"","tooltip":"","permission":"blog.view","config_boolean":"blog-enabled","children":[{"text":"Blog Posts","href":"","icon":"fa fa-newspaper-o","target":"_self","title":"","auth":"true","page":"admin-blog","guest":"false","roles":[],"active":["admin-blog","admin-blog-categories-edit","admin-blog-edit","admin-blog-tags-edit"],"classes":[],"html_id":"","tooltip":"","permission":"blog.view"},{"text":"Comments","href":"","icon":"fa fa-comment","target":"_self","title":"","auth":"true","page":"admin-blog-comments","guest":"false","roles":[],"active":["admin-blog-comment-details","admin-blog-comments"],"classes":[],"html_id":"","tooltip":"","permission":"blog.view"},{"text":"New Post","href":"","icon":"fa fa-plus","target":"_self","title":"","auth":"true","page":"admin-blog-add","guest":"false","roles":[],"active":["admin-blog-add"],"classes":[],"html_id":"","tooltip":"","permission":"blog.create"}]},{"text":"Local CMS","href":"","icon":"fa fa-image","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":[],"classes":[],"html_id":"media-menu","tooltip":"","permission":"media.local"},{"text":"Cloudinary CMS","href":"","icon":"fa fa-soundcloud","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":[],"classes":[],"html_id":"cloudinary-menu","tooltip":"","permission":"media.cloudinary"},{"text":"Contact Requests","href":"","icon":"fa fa-address-book","target":"_self","title":"","auth":"true","page":"admin-contact","guest":"false","roles":[],"active":["admin-contact"],"classes":[],"html_id":"","tooltip":"","permission":"contact.view"},{"text":"Oauth2 Providers","href":"","icon":"fa fa-user-circle","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":["admin-oauth2","admin-oauth2-add","admin-oauth2-edit"],"classes":[],"html_id":"","tooltip":"","permission":"oauth2.view","config_boolean":"oauth2-enabled","children":[{"text":"Providers","href":"","icon":"fa fa-codepen","target":"_self","title":"","auth":"true","page":"admin-oauth2","guest":"false","roles":[],"active":["admin-oauth2","admin-oauth2-edit"],"classes":[],"html_id":"","tooltip":"","permission":"oauth2.view"},{"text":"New Provider","href":"","icon":"fa fa-plus","target":"_self","title":"","auth":"true","page":"admin-oauth2-add","guest":"false","roles":[],"active":["admin-oauth2-add"],"classes":[],"html_id":"","tooltip":"","permission":"oauth2.create"}]},{"text":"SEO","href":"","icon":"fa fa-sitemap","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":["admin-seo","admin-seo-add","admin-seo-edit"],"classes":[],"html_id":"","tooltip":"","permission":"seo.view","children":[{"text":"All Configs","href":"","icon":"fa fa-sitemap","target":"_self","title":"","auth":"true","page":"admin-seo","guest":"false","roles":[],"active":["admin-seo-add","admin-seo-edit"],"classes":[],"html_id":"","tooltip":"","permission":"seo.update"},{"text":"New SEO Config","href":"","icon":"fa fa-plus","target":"_self","title":"","auth":"true","page":"admin-seo-add","guest":"false","roles":[],"active":["admin-seo-add"],"classes":[],"html_id":"","tooltip":"","permission":"seo.create"}]},{"text":"Pages","href":"","icon":"fa fa-book","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":[],"active":["admin-pages","admin-pages-add","admin-pages-edit"],"classes":[],"html_id":"","tooltip":"","permission":"pages.view","children":[{"text":"All Pages","href":"","icon":"fa fa-bookmark","target":"_self","title":"","auth":"true","page":"admin-pages","guest":"false","roles":[],"active":["admin-pages","admin-pages-edit"],"classes":[],"html_id":"","tooltip":"","permission":"pages.view"},{"text":"New Page","href":"","icon":"fa fa-plus","target":"_self","title":"","auth":"true","page":"admin-pages-add","guest":"false","roles":[],"active":["admin-pages-add"],"classes":[],"html_id":"","tooltip":"","permission":"pages.create"}]},{"text":"Menus","href":"","icon":"fa fa-map","target":"_self","title":"","auth":"true","page":"admin-menus","guest":"false","roles":[],"active":["admin-menus"],"classes":[],"html_id":"","tooltip":"","permission":"menus.update"},{"text":"Global Settings","href":"","icon":"fa fa-gears","target":"_self","title":"","auth":"true","page":"settings-global","guest":"false","roles":[],"active":["settings-global"],"classes":[],"html_id":"","tooltip":"","permission":"settings.global"},{"text":"Developer Tools","href":"","icon":"fa fa-life-bouy","target":"_self","title":"","auth":"true","page":"","guest":"false","roles":["developer"],"active":["developer-logs"],"classes":[],"html_id":"","tooltip":"","permission":"settings.developer","children":[{"text":"Logfiles","href":"","icon":"fa fa-clipboard","target":"_self","title":"","auth":"true","page":"developer-logs","guest":"false","roles":["developer"],"active":["developer-logs"],"classes":[],"html_id":"","tooltip":"","permission":"settings.developer"}]}]'; $ins->save(); // Update Admin Role $admin_role = $this->sentinel->findRoleByName('Admin'); $admin_role->addPermission('menus.*'); $admin_role->save(); // Add Menu Config Types $configType = new Dappur\Model\ConfigTypes; $configType->name = 'menu'; $configType->save(); // Add Dappur Menu to Site Config $addMenu = new Dappur\Model\Config; $addMenu->group_id = 1; $addMenu->name = 'site-menu'; $addMenu->description = "Site Menu"; $addMenu->type_id = $configType->id; $addMenu->value = 1; $addMenu->save(); // Add Dappur Menu to Site Config $addMenu2 = new Dappur\Model\Config; $addMenu2->group_id = 2; $addMenu2->name = 'dashboard-menu'; $addMenu2->description = "Dashboard Menu"; $addMenu2->type_id = $configType->id; $addMenu2->value = 2; $addMenu2->save(); }
Write your reversible migrations using this method. Dappur Framework uses Laravel Eloquent ORM as it's database connector. More information on writing eloquent migrations is available here: https://laravel.com/docs/5.4/migrations Remember to use both the up() and down() functions in order to be able to roll back. Create Table Sample: $this->schema->create('sample', function (Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); $table->string('last_name')->nullable(); $table->string('first_name')->nullable(); $table->timestamps(); }); Drop Table Sample: $this->schema->dropIfExists('sample');
entailment
protected function setError($conn = null) { // is conn resource provided, or do we get last error? if ($conn) { $this->setErrorCode(odbc_error($conn)); $this->setErrorMsg(odbc_errormsg($conn)); } else { $this->setErrorCode(odbc_error()); $this->setErrorMsg(odbc_errormsg()); } }
set error code and message based on last odbc connection/prepare/execute error. @todo: consider using GET DIAGNOSTICS for even more message text: http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Frzala%2Frzalafinder.htm @param null $conn
entailment
public function execXMLStoredProcedure($conn, $stmt, $bindArray) { $crsr = odbc_prepare($conn, $stmt); if (!$crsr) { $this->setError($conn); return false; } // extension problem: sends warning message into the php_log or stdout // about number of result sets. (switch on return code of SQLExecute() // SQL_SUCCESS_WITH_INFO if (!@odbc_execute($crsr , array($bindArray['internalKey'], $bindArray['controlKey'], $bindArray['inputXml']))) { $this->setError($conn); return "ODBC error code: " . $this->getErrorCode() . ' msg: ' . $this->getErrorMsg(); } // disconnect operation cause crush in fetch, nothing appears as sql script. $row=''; $outputXML = ''; if (!$bindArray['disconnect']) { while (odbc_fetch_row($crsr)) { $tmp = odbc_result($crsr, 1); if ($tmp) { // because of ODBC problem blob transferring should execute some "clean" on returned data if (strstr($tmp , "</script>")) { $pos = strpos($tmp, "</script>"); $pos += strlen("</script>"); // @todo why append this value? $row .= substr($tmp, 0, $pos); break; } else { $row .= $tmp; } } } $outputXML = $row; } return $outputXML; }
this function used for special stored procedure call only @param $conn @param $stmt @param $bindArray @return string
entailment
public function singlePcmlToArray(\SimpleXmlElement $dataElement) { $tagName = $dataElement->getName(); // get attributes of this element. $attrs = $dataElement->attributes(); // both struct and data have name, count (optional), usage $name = (isset($attrs['name'])) ? (string) $attrs['name'] : ''; $count = (isset($attrs['count'])) ? (string) $attrs['count'] : ''; $usage = (isset($attrs['usage'])) ? (string) $attrs['usage'] : ''; $structName = (isset($attrs['struct'])) ? (string) $attrs['struct'] : ''; // fill this if we have a struct $subElements = array(); // should all be data if ($tagName == 'data') { $type = (isset($attrs['type'])) ? (string) $attrs['type'] : ''; // if a struct then we need to recurse. if ($type != 'struct') { // regular type (char, int...), not a struct, so the data element's name is just 'name'. $nameName = 'Name'; } else { // it IS a struct. // old toolkit uses DSName for a data structure's name. $nameName = 'DSName'; $theStruct = null; // init // look for matching struct if ($this->_pcmlStructs) { // TODO verify type with is_array and count foreach ($this->_pcmlStructs as $possibleStruct) { $possStructAttrs = $possibleStruct->attributes(); if ($possStructAttrs['name'] == $structName) { $theStruct = $possibleStruct; $structAttrs = $possStructAttrs; break; } } } // if struct was not found, generate error for log if (!$theStruct) { // $this->getConnection->logThis("PCML structure '$structName' not found."); return null; } // if we got here, we found our struct. // count can also be defined at the structure level. If so, it will override count from data level) if (isset($structAttrs['count'])) { $count = (string) $structAttrs['count']; } // "usage" (in/out/inherit) can be defined here, at the structure level. $structUsage = (isset($structAttrs['usage'])) ? (string) $structAttrs['usage'] : ''; // if we're not inheriting from our parent data element, but there is a struct usage, use the struct's usage (input, output, or inputoutput). if (!empty($structUsage) && ($structUsage != 'inherit')) { $usage = $structUsage; } $structSubDataElementsXmlObj = $theStruct->xpath('data'); if ($structSubDataElementsXmlObj) { foreach ($structSubDataElementsXmlObj as $subDataElementXmlObj) { if ($subDataElementXmlObj->attributes()->usage == 'inherit') { // subdata is inheriting type from us. Give it to them. $subDataElementXmlObj->attributes()->usage = $usage; } // here's where the recursion comes in. Convert data and add to array for our struct. $subElements[] = $this->singlePcmlToArray($subDataElementXmlObj); } } } $length = (isset($attrs['length'])) ? (string) $attrs['length'] : ''; $precision = (isset($attrs['precision'])) ? (string) $attrs['precision'] : ''; //$struct = (isset($attrs['struct'])) ? (string) $attrs['struct'] : ''; // if this is pointing to a struct name // find CW data type equivalent of PCML data type if (isset($this->_pcmlTypeMap[$type])) { // a simple type mapping $newType = (string) $this->_pcmlTypeMap[$type]; } elseif ($type == 'int') { // one of the integer types. Need to use length to determine which one. if ($length == '2') { $newType = I5_TYPE_SHORT; } elseif ($length == '4') { $newType = I5_TYPE_INT; } else { $newType = ''; // no match } } else { $newtype = ''; } $newInout = (isset($this->_pcmlInoutMap[$usage])) ? (string) $this->_pcmlInoutMap[$usage] : ''; // create new length using precision if necessary if ($precision) { $newLength = "$length.$precision"; } else { $newLength = $length; } } // count $newCount = 0; // initialize $newCountRef = ''; if (is_numeric($count) && ($count > 0)) { $newCount = $count; } elseif (is_string($count) && !empty($count)) { // count is character, so it's really a countref $newCountRef = $count; } $element = array(); $element[$nameName] = $name; // if not a struct, provide data type. if ($type != 'struct') { $element['Type'] = $newType; } if ($newCount) { $element['Count'] = $newCount; } if ($newCountRef) { $element['CountRef'] = $newCountRef; } if ($newLength) { $element['Length'] = $newLength; } if ($newInout) { $element['IO'] = $newInout; } if (count($subElements)) { $element['DSParm'] = $subElements; } return $element; }
given a single ->data or ->struct element, return an array containing its contents as old toolkit-style data description. @param \SimpleXmlElement $dataElement @return array
entailment
public function pcmlToArray(\SimpleXMLElement $xmlObj) { $dataDescription = array(); // put structs in its own variable that can be accessed independently. $this->_pcmlStructs = $xmlObj->xpath('struct'); // looking for ->data and ->struct. $dataElements = $xmlObj->xpath('program/data'); if ($dataElements) { foreach ($dataElements as $dataElement) { $dataDescription[] = $this->singlePcmlToArray($dataElement); } } return $dataDescription; }
given an XML object containing a PCML program definition, return an old toolkit style of data description array. @param \SimpleXMLElement $xmlObj @return array
entailment
public function createDataArea($DataAreaName = '', $DataAreaLib = "*CURLIB", $size = 2000) { if ($DataAreaName !='' && $this->DataAreaName == NULL) { /*was not set before*/ $this->setDataAreaName($DataAreaName , $DataAreaLib); } if ($size > 2000 || $size <= 0) { $dataAreaLen = 2000; } else { $dataAreaLen = $size; } $cmd = sprintf("QSYS/CRTDTAARA DTAARA(%s/%s) TYPE(*CHAR) LEN($dataAreaLen)", ($DataAreaLib != '' ? $DataAreaLib : $this->DataAreaLib), ($DataAreaName !='' ? $DataAreaName : $this->DataAreaName)); // @todo get CPF code if (!$this->ToolkitSrvObj->CLCommand($cmd)) { $this->ErrMessage = "Create Data Area failed." . $this->ToolkitSrvObj->getLastError(); throw new \Exception($this->ErrMessage); } return true; }
for *char data area. According to create other data area types use CL command @param string $DataAreaName @param string $DataAreaLib *CURLIB is correct, the default with CRTDTAARA. @param int $size @return bool @throws \Exception
entailment
public function setDataAreaName($dataAreaName, $dataAreaLib = "*LIBL") { /** * special values: * LDA Local data area * GDA Group data area * PDA Program initialization parameter data area */ $dataAreaName = trim(strtoupper($dataAreaName)); if ($dataAreaName == '') { throw new \Exception("Data Area name parameter should be defined "); } // no library allowed for these special values. if (in_array($dataAreaName, array('*LDA', '*GDA', '*PDA'))) { $dataAreaLib = ''; } $this->DataAreaName = $dataAreaName; $this->DataAreaLib = $dataAreaLib; }
*LIBL to read/write data area. *CURLIB to create. @param $dataAreaName @param string $dataAreaLib @throws \Exception
entailment
public function deleteDataArea($DataAreaName = '', $DataAreaLib = '') { $cmd = sprintf("QSYS/DLTDTAARA DTAARA(%s/%s)", ($DataAreaLib != '' ? $DataAreaLib : $this->DataAreaLib), ($DataAreaName != NULL ? $DataAreaName : $this->DataAreaName)); if (!$this->ToolkitSrvObj->CLCommand($cmd)) { $this->ErrMessage = "Delete Data Area failed." . $this->ToolkitSrvObj->getLastError(); throw new \Exception($this->ErrMessage); } }
requires explicit library @param string $DataAreaName @param string $DataAreaLib @throws \Exception
entailment
public function write(Response $response, $data, $status = 200) { return $response->withStatus($status)->getBody()->write($data); }
Write text in the response body @param Response $response @param string $data @param int $status @return int
entailment
public function onCorsPreflight(MvcEvent $event) { // Reset state flag $this->isPreflight = false; /** @var $request HttpRequest */ $request = $event->getRequest(); if (! $request instanceof HttpRequest) { return; } try { $isCorsRequest = $this->corsService->isCorsRequest($request); } catch (InvalidOriginException $exception) { /** @var HttpResponse $response */ $response = $event->getResponse(); $response->setStatusCode(400); $response->setReasonPhrase($exception->getMessage()); return $response; } // If this isn't a preflight, done if (! $isCorsRequest || ! $this->corsService->isPreflightRequest($request)) { return; } // Preflight -- return a response now! $this->isPreflight = true; return $this->corsService->createPreflightCorsResponseWithRouteOptions($request, $event->getRouteMatch()); }
Handle a CORS preflight request @param MvcEvent $event @return null|HttpResponse
entailment
public function onCorsRequest(MvcEvent $event) { // Do nothing if we previously created a preflight response if ($this->isPreflight) { return; } /** @var $request HttpRequest */ $request = $event->getRequest(); /** @var $response HttpResponse */ $response = $event->getResponse(); if (! $request instanceof HttpRequest) { return; } try { $isCorsRequest = $this->corsService->isCorsRequest($request); } catch (InvalidOriginException $exception) { // InvalidOriginException should already be handled by `CorsRequestListener::onCorsPreflight` return; } // Also ensure that the vary header is set when no origin is set // to prevent reverse proxy caching a wrong request; causing all of the following // requests to fail due to missing CORS headers. if (! $isCorsRequest) { if (! $request->getHeader('Origin')) { $this->corsService->ensureVaryHeader($response); } return; } // This is the second step of the CORS request, and we let ZF continue // processing the response try { $response = $this->corsService->populateCorsResponse($request, $response); } catch (DisallowedOriginException $exception) { $response = new HttpResponse(); // Clear response for security $response->setStatusCode(403) ->setReasonPhrase($exception->getMessage()); } $event->setResponse($response); }
Handle a CORS request (non-preflight, normal CORS request) @param MvcEvent $event
entailment
public function onBootstrap(EventInterface $event) { /* @var $application \Zend\Mvc\Application */ $application = $event->getTarget(); $serviceManager = $application->getServiceManager(); $eventManager = $application->getEventManager(); /** @var \ZfrCors\Mvc\CorsRequestListener $listener */ $listener = $serviceManager->get('ZfrCors\Mvc\CorsRequestListener'); $listener->attach($eventManager); }
{@inheritDoc}
entailment
public function getConfigFile($name, $required = true, $directory = 'config') { $sep = DIRECTORY_SEPARATOR; $path = rtrim($this->directory, $sep) . $sep . trim($directory, $sep) . $sep . $name; if (!file_exists($path)) { if ($required) { throw new \Exception("Config file '$path' does not exist"); } else { return null; } } return $path; }
Gets the filename for a config file @param string $name @param bool $required whether the file must exist. Default is `true`. @param string $directory the name of the config directory. Default is `config`. @return string|null the full path to the config file or `null` if $required is set to `false` and the file does not exist @throws \Exception
entailment
public function web($config = [], $local = null) { $files = [$this->getConfigFile('web.php')]; if ($local === null) { $local = $this->env('ENABLE_LOCALCONF', false); } if ($local) { $localFile = $this->getConfigFile('local.php', false); if ($localFile !==null) { $files[] = $localFile; } } return $this->mergeFiles($files, $config); }
Builds the web configuration. If $local is set to `true` and a `local.php` config file exists, it is merged into the web configuration. Alternatively an environment variable `ENABLE_LOCALCONF` can be set to 1. Setting $local to `false` completely disables the local config. @param array $config additional configuration to merge into the result @param bool|null $local whether to check for local configuration overrides. The default is `null`, which will check `ENABLE_LOCALCONF` env var. @return array the web configuration array @throws \Exception
entailment
public function mergeFiles($files, $config = []) { $configs = array_map(function ($f) { return require($f); }, $files); $configs[] = $config; return call_user_func_array('yii\helpers\ArrayHelper::merge', $configs); }
Load configuration files and merge them together. The files are loaded in the context of this class. So you can use `$this` and `self` to access instance / class methods. @param array $files list of configuration files to load and merge. Configuration from later files will override earlier values. @param array $config additional configuration to merge into the result @return array the resulting configuration array
entailment
public static function bootstrap($directory, $vendor = null, $initEnv = true) { $sep = DIRECTORY_SEPARATOR; if ($vendor === null) { $vendor = realpath(__DIR__ . $sep . '..' . $sep . '..' . $sep . '..'); } $config = new self($directory, $initEnv); require(rtrim($vendor, $sep) . $sep . 'yiisoft' . $sep . 'yii2' . $sep . 'Yii.php'); return $config; }
Init the configuration for the given directory and load the Yii bootstrap file. @param string $directory the application directory @param string|null $vendor the composer vendor directory. Default is `null` which means, the vendor directory is autodetected. @param bool $initEnv whether to initialize the Yii environment. Default is `true`. @return static the Config instance for that application directory
entailment
public static function initEnv($directory = null) { if ($directory !== null && file_exists($directory . DIRECTORY_SEPARATOR . '.env')) { $dotenv = new \Dotenv\Dotenv($directory); $dotenv->load(); } // Define main Yii environment variables $debug = self::env('YII_DEBUG', false); if ($debug !== false) { define('YII_DEBUG', (bool)$debug); if (YII_DEBUG) { error_reporting(E_ALL); } } $env = self::env('YII_ENV', false); if ($env !== false) { define('YII_ENV', $env); } }
Init the Yii environment from environment variables. If $directory is passed and contains a `.env` file, that file is loaded with `Dotenv` first. @param string|null $directory the directory to check for an `.env` file
entailment
public function isCorsRequest(HttpRequest $request) { $headers = $request->getHeaders(); if (! $headers->has('Origin')) { return false; } try { $origin = $headers->get('Origin'); } catch (Header\Exception\InvalidArgumentException $exception) { throw InvalidOriginException::fromInvalidHeaderValue(); } $originUri = UriFactory::factory($origin->getFieldValue()); $requestUri = $request->getUri(); // According to the spec (http://tools.ietf.org/html/rfc6454#section-4), we should check host, port and scheme return (! ($originUri->getHost() === $requestUri->getHost()) || ! ($originUri->getPort() === $requestUri->getPort()) || ! ($originUri->getScheme() === $requestUri->getScheme()) ); }
Check if the HTTP request is a CORS request by checking if the Origin header is present and that the request URI is not the same as the one in the Origin @param HttpRequest $request @return bool
entailment
public function isPreflightRequest(HttpRequest $request) { return $this->isCorsRequest($request) && strtoupper($request->getMethod()) === 'OPTIONS' && $request->getHeaders()->has('Access-Control-Request-Method'); }
Check if the CORS request is a preflight request @param HttpRequest $request @return bool
entailment
public function createPreflightCorsResponse(HttpRequest $request) { $response = new HttpResponse(); $response->setStatusCode(200); $headers = $response->getHeaders(); $headers->addHeaderLine('Access-Control-Allow-Origin', $this->getAllowedOriginValue($request)); $headers->addHeaderLine('Access-Control-Allow-Methods', implode(', ', $this->options->getAllowedMethods())); $headers->addHeaderLine('Access-Control-Allow-Headers', implode(', ', $this->options->getAllowedHeaders())); $headers->addHeaderLine('Access-Control-Max-Age', $this->options->getMaxAge()); $headers->addHeaderLine('Content-Length', 0); if ($this->options->getAllowedCredentials()) { $headers->addHeaderLine('Access-Control-Allow-Credentials', 'true'); } return $response; }
Create a preflight response by adding the corresponding headers @param HttpRequest $request @return HttpResponse
entailment
public function createPreflightCorsResponseWithRouteOptions(HttpRequest $request, $routeMatch = null) { $options = $this->options; if ($routeMatch instanceof RouteMatch || $routeMatch instanceof DeprecatedRouteMatch) { $options->setFromArray($routeMatch->getParam(CorsOptions::ROUTE_PARAM) ?: []); } $response = $this->createPreflightCorsResponse($request); return $response; }
Create a preflight response by adding the correspoding headers which are merged with per-route configuration @param HttpRequest $request @param RouteMatch|DeprecatedRouteMatch|null $routeMatch @return HttpResponse
entailment
public function populateCorsResponse(HttpRequest $request, HttpResponse $response) { $origin = $this->getAllowedOriginValue($request); // If $origin is "null", then it means than the origin is not allowed. As this is // a simple request, it is useless to continue the processing as it will be refused // by the browser anyway, so we throw an exception if ($origin === 'null') { $origin = $request->getHeader('Origin'); $originHeader = $origin ? $origin->getFieldValue() : ''; throw new DisallowedOriginException( sprintf( 'The origin "%s" is not authorized', $originHeader ) ); } $headers = $response->getHeaders(); $headers->addHeaderLine('Access-Control-Allow-Origin', $origin); $headers->addHeaderLine('Access-Control-Expose-Headers', implode(', ', $this->options->getExposedHeaders())); $headers = $this->ensureVaryHeader($response); if ($this->options->getAllowedCredentials()) { $headers->addHeaderLine('Access-Control-Allow-Credentials', 'true'); } $response->setHeaders($headers); return $response; }
Populate a simple CORS response @param HttpRequest $request @param HttpResponse $response @return HttpResponse @throws DisallowedOriginException If the origin is not allowed
entailment
protected function getAllowedOriginValue(HttpRequest $request) { $allowedOrigins = $this->options->getAllowedOrigins(); $origin = $request->getHeader('Origin'); if ($origin) { $origin = $origin->getFieldValue(); if (in_array('*', $allowedOrigins)) { return $origin; } foreach ($allowedOrigins as $allowedOrigin) { if (fnmatch($allowedOrigin, $origin)) { return $origin; } } } return 'null'; }
Get a single value for the "Access-Control-Allow-Origin" header According to the spec, it is not valid to set multiple origins separated by commas. Only accepted value are wildcard ("*"), an exact domain or a null string. @link http://www.w3.org/TR/cors/#access-control-allow-origin-response-header @param HttpRequest $request @return string
entailment
public function ensureVaryHeader(HttpResponse $response) { $headers = $response->getHeaders(); // If the origin is not "*", we should add the "Origin" value to the "Vary" header // See more: http://www.w3.org/TR/cors/#resource-implementation $allowedOrigins = $this->options->getAllowedOrigins(); if (in_array('*', $allowedOrigins)) { return $headers; } if ($headers->has('Vary')) { $varyHeader = $headers->get('Vary'); $varyValue = $varyHeader->getFieldValue() . ', Origin'; $headers->removeHeader($varyHeader); $headers->addHeaderLine('Vary', $varyValue); } else { $headers->addHeaderLine('Vary', 'Origin'); } return $headers; }
Ensure that the Vary header is set. @link http://www.w3.org/TR/cors/#resource-implementation @param HttpResponse $response @return \Zend\Http\Headers
entailment
public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if ($tokens[$stackPtr]['code'] === T_IS_NOT_EQUAL) { $error = '"%s" is not allowed, use "!==" instead'; $data = array($tokens[$stackPtr]['content']); $fix = $phpcsFile->addFixableError($error, $stackPtr, 'IsNotEqualNotAllowed', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $phpcsFile->fixer->replaceToken($stackPtr, '!=='); $phpcsFile->fixer->endChangeset(); } } }
Processes this test, when one of its tokens is encountered. @param File $phpcsFile The current file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
public function register() { // Everyone has had a chance to figure out what forbidden functions // they want to check for, so now we can cache out the list. $this->forbiddenFunctionNames = array_keys($this->forbiddenFunctions); if ($this->patternMatch === true) { foreach ($this->forbiddenFunctionNames as $i => $name) { $this->forbiddenFunctionNames[$i] = '/'.$name.'/i'; } return array(T_STRING); } // If we are not pattern matching, we need to work out what // tokens to listen for. $string = '<?php '; foreach ($this->forbiddenFunctionNames as $name) { $string .= $name.'();'; } $register = array(); $tokens = token_get_all($string); array_shift($tokens); foreach ($tokens as $token) { if (is_array($token) === true) { $register[] = $token[0]; } } return array_unique($register); }
Returns an array of tokens this test wants to listen for. @return array
entailment
public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $ignore = array( T_DOUBLE_COLON => true, T_FUNCTION => true, T_CONST => true, T_PUBLIC => true, T_PRIVATE => true, T_PROTECTED => true, T_AS => true, T_NEW => true, T_INSTEADOF => true, T_NS_SEPARATOR => true, T_IMPLEMENTS => true, ); $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); // If function call is directly preceded by a NS_SEPARATOR it points to the // global namespace, so we should still catch it. if ($tokens[$prevToken]['code'] === T_NS_SEPARATOR) { $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($prevToken - 1), null, true); if ($tokens[$prevToken]['code'] === T_STRING) { // Not in the global namespace. return; } } if (isset($ignore[$tokens[$prevToken]['code']]) === true) { // Not a call to a PHP function. return; } $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); if (isset($ignore[$tokens[$nextToken]['code']]) === true) { // Not a call to a PHP function. return; } if ($tokens[$stackPtr]['code'] === T_STRING && $tokens[$nextToken]['code'] !== T_OPEN_PARENTHESIS) { // Not a call to a PHP function. return; } $function = strtolower($tokens[$stackPtr]['content']); $pattern = null; if ($this->patternMatch === true) { $count = 0; $pattern = preg_replace( $this->forbiddenFunctionNames, $this->forbiddenFunctionNames, $function, 1, $count ); if ($count === 0) { return; } // Remove the pattern delimiters and modifier. $pattern = substr($pattern, 1, -2); } else { if (in_array($function, $this->forbiddenFunctionNames) === false) { return; } }//end if $this->addError($phpcsFile, $stackPtr, $function, $pattern); }
Processes this test, when one of its tokens is encountered. @param File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
protected function addError($phpcsFile, $stackPtr, $function, $pattern=null) { $data = array($function); $error = 'The use of function %s() is '; if ($this->error === true) { $type = 'Found'; $error .= 'forbidden'; } else { $type = 'Discouraged'; $error .= 'discouraged'; } if ($pattern === null) { $pattern = $function; } if ($this->forbiddenFunctions[$pattern] !== null && $this->forbiddenFunctions[$pattern] !== 'null' ) { $type .= 'WithAlternative'; $data[] = $this->forbiddenFunctions[$pattern]; $error .= '; use %s() instead'; } if ($this->error === true) { $phpcsFile->addError($error, $stackPtr, $type, $data); } else { $phpcsFile->addWarning($error, $stackPtr, $type, $data); } }
Generates the error or warning for this sniff. @param File $phpcsFile The file being scanned. @param int $stackPtr The position of the forbidden function in the token array. @param string $function The name of the forbidden function. @param string $pattern The pattern used for the match. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $this->currentFile = $phpcsFile; $tokens = $phpcsFile->getTokens(); $type = strtolower($tokens[$stackPtr]['content']); $errorData = array($type); $find = Tokens::$methodPrefixes; $find[] = T_WHITESPACE; $commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true); if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG && $tokens[$commentEnd]['code'] !== T_COMMENT ) { $phpcsFile->addError('Missing class doc comment', $stackPtr, 'Missing'); $phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'no'); return; } else { $phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'yes'); } // Try and determine if this is a file comment instead of a class comment. // We assume that if this is the first comment after the open PHP tag, then // it is most likely a file comment instead of a class comment. if ($tokens[$commentEnd]['code'] === T_DOC_COMMENT_CLOSE_TAG) { $start = ($tokens[$commentEnd]['comment_opener'] - 1); } else { $start = $phpcsFile->findPrevious(T_COMMENT, ($commentEnd - 1), null, true); } $prev = $phpcsFile->findPrevious(T_WHITESPACE, $start, null, true); if ($tokens[$prev]['code'] === T_OPEN_TAG) { $prevOpen = $phpcsFile->findPrevious(T_OPEN_TAG, ($prev - 1)); if ($prevOpen === false) { // This is a comment directly after the first open tag, // so probably a file comment. $phpcsFile->addError('Missing class doc comment', $stackPtr, 'Missing'); return; } } if ($tokens[$commentEnd]['code'] === T_COMMENT) { $phpcsFile->addError('You must use "/**" style comments for a class comment', $stackPtr, 'WrongStyle'); return; } // Check each tag. $this->processTags($phpcsFile, $stackPtr, $tokens[$commentEnd]['comment_opener']); }
Processes this test, when one of its tokens is encountered. @param File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
protected function processMemberVar(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $varName = ltrim($tokens[$stackPtr]['content'], '$'); $memberProps = $phpcsFile->getMemberProperties($stackPtr); if (empty($memberProps) === true) { // Couldn't get any info about this variable, which // generally means it is invalid or possibly has a parse // error. Any errors will be reported by the core, so // we can ignore it. return; } // Methods must not be prefixed with an underscore except those allowed in publicMethodNames. if (substr($varName, 0, 1) === '_') { if (isset(Common::$publicMethodNames[$varName]) === false) { $scope = $memberProps['scope']; $errorData = array($varName); $error = ucfirst($scope).' property "%s" must not be prefixed with an underscore'; $phpcsFile->addError($error, $stackPtr, 'PropertyMustNotHaveUnderscore', $errorData); return; } } if (Common::isCamelCaps($varName, false, true, false) === false) { $errorData = array($varName); $error = 'Property "%s" is not in valid camel caps format'; $phpcsFile->addError($error, $stackPtr, 'PropertyNotLowerCamelCase', $errorData); } }
Processes class member variables. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
protected function processVariableInString(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $phpReservedVars = array( '_SERVER', '_GET', '_POST', '_REQUEST', '_SESSION', '_ENV', '_COOKIE', '_FILES', 'GLOBALS', 'http_response_header', 'HTTP_RAW_POST_DATA', 'php_errormsg', ); if (preg_match_all('|[^\\\]\${?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)|', $tokens[$stackPtr]['content'], $matches) !== 0) { foreach ($matches[1] as $varName) { // If it's a php reserved var, then its ok. if (in_array($varName, $phpReservedVars) === true) { continue; } if (Common::isCamelCaps($varName, false, true, false) === false) { $error = 'Variable "%s" is not in valid camel caps format'; $data = array($varName); $phpcsFile->addError($error, $stackPtr, 'StringNotCamelCaps', $data); } } } }
Processes the variable found within a double quoted string. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the double quoted string. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $errors = array(); $tokens = $phpcsFile->getTokens(); for ($i = 1; $i < $phpcsFile->numTokens; $i++) { $nextContentPtr = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), null, true); $lines = ($tokens[$nextContentPtr]['line'] - $tokens[$i]['line'] - 1); $errorLine = (($nextContentPtr - $lines) + $this->allowed - 1); if ($lines > ($this->allowed) && in_array($errorLine, $errors) === false) { $errors[] = $errorLine; $data = array( $this->allowed, Common::pluralize('line', $this->allowed), ); $error = 'Expected only %s empty %s'; $fix = $phpcsFile->addFixableError($error, $errorLine, 'VerticalEmptyLines', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken($errorLine, ''); } } } // Ignore the rest of the file. return ($phpcsFile->numTokens + 1); }
Processes this test, when one of its tokens is encountered. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return int
entailment
public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $nextToken = $tokens[($stackPtr + 1)]; if (T_WHITESPACE !== $nextToken['code']) { $error = 'There must be a space after !'; $fix = $phpcsFile->addFixableError($error, $stackPtr, 'BooleanNotNoWhiteSpaceAfter'); if ($fix === true) { $nextContentPtr = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); $phpcsFile->fixer->beginChangeset(); for ($i = ($nextContentPtr + 1); $i < $stackPtr; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->addContent(($stackPtr), ' '); $phpcsFile->fixer->endChangeset(); $phpcsFile->recordMetric($stackPtr, 'Boolean not space after', 'yes'); }//end if }//end if }
Processes this test, when one of its tokens is encountered. @param File $phpcsFile The current file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if (isset($tokens[$stackPtr]['scope_closer']) === false) { // Probably an interface method. return; } $closeBrace = $tokens[$stackPtr]['scope_closer']; $prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($closeBrace - 1), null, true); // Special case for empty JS functions. if ($phpcsFile->tokenizerType === 'JS' && $prevContent === $tokens[$stackPtr]['scope_opener']) { // In this case, the opening and closing brace must be // right next to each other. if ($tokens[$stackPtr]['scope_closer'] !== ($tokens[$stackPtr]['scope_opener'] + 1)) { $error = 'The opening and closing braces of empty functions must be directly next to each other; e.g., function () {}'; $fix = $phpcsFile->addFixableError($error, $closeBrace, 'SpacingBetween'); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); for ($i = ($tokens[$stackPtr]['scope_opener'] + 1); $i < $closeBrace; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->endChangeset(); } } return; } $nestedFunction = false; if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION) === true || $phpcsFile->hasCondition($stackPtr, T_CLOSURE) === true || isset($tokens[$stackPtr]['nested_parenthesis']) === true ) { $nestedFunction = true; } $braceLine = $tokens[$closeBrace]['line']; $prevLine = $tokens[$prevContent]['line']; $found = ($braceLine - $prevLine - 1); $afterKeyword = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); $beforeKeyword = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); if ($nestedFunction === true) { if ($found < 0) { $error = 'Closing brace of nested function must be on a new line'; $fix = $phpcsFile->addFixableError($error, $closeBrace, 'ContentBeforeClose'); if ($fix === true) { $phpcsFile->fixer->addNewlineBefore($closeBrace); } } else if ($found > $this->allowedNestedLines) { $error = 'Expected %s blank lines before closing brace of nested function; %s found'; $data = array( $this->allowedNestedLines, $found, ); $fix = $phpcsFile->addFixableError($error, $closeBrace, 'SpacingBeforeNestedClose', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $changeMade = false; for ($i = ($prevContent + 1); $i < $closeBrace; $i++) { // Try to maintain indentation. if ($tokens[$i]['line'] === ($braceLine - 1)) { break; } $phpcsFile->fixer->replaceToken($i, ''); $changeMade = true; } // Special case for when the last content contains the newline // token as well, like with a comment. if ($changeMade === false) { $phpcsFile->fixer->replaceToken(($prevContent + 1), ''); } $phpcsFile->fixer->endChangeset(); }//end if }//end if } else { if ($found !== (int) $this->allowedLines) { if ($this->allowedLines === 1) { $plural = ''; } else { $plural = 's'; } $error = 'Expected %s blank line%s before closing function brace; %s found'; $data = array( $this->allowedLines, $plural, $found, ); $fix = $phpcsFile->addFixableError($error, $closeBrace, 'SpacingBeforeClose', $data); if ($fix === true) { if ($found > $this->allowedLines) { $phpcsFile->fixer->beginChangeset(); for ($i = ($prevContent + 1); $i < ($closeBrace); $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->replaceToken(($closeBrace - 1), $phpcsFile->eolChar); $phpcsFile->fixer->endChangeset(); } else { $phpcsFile->fixer->addNewlineBefore($closeBrace); } } }//end if }//end if }
Processes this test, when one of its tokens is encountered. @param File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); // Scope keyword should be on a new line. if (isset($tokens[$stackPtr]['scope_opener']) === true || $tokens[$stackPtr]['code'] === T_WHILE || $tokens[($stackPtr)]['code'] === T_ELSE ) { // If this is alternate syntax ":" instead of "{" then skip it. if (isset($tokens[$stackPtr]['scope_opener']) === true) { $openingBracePtr = $tokens[$stackPtr]['scope_opener']; if ($tokens[$openingBracePtr]['code'] === T_COLON) { return; } } $prevContentPtr = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); // Skip if this T_IF is part of an else if. if ($tokens[($stackPtr)]['code'] !== T_IF && $tokens[($prevContentPtr)]['code'] !== T_ELSE ) { $keywordLine = $tokens[($stackPtr)]['line']; $prevContentLine = $tokens[($prevContentPtr)]['line']; if ($keywordLine === $prevContentLine) { $data = array($tokens[$stackPtr]['content']); $error = 'Scope keyword "%s" should be on a new line'; $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ScopeKeywordOnNewLine', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $phpcsFile->fixer->addNewlineBefore($stackPtr); $phpcsFile->fixer->endChangeset(); } } } }//end if // Expect 1 space after keyword, Skip T_ELSE, T_DO, T_TRY. if (isset($tokens[$stackPtr]['scope_opener']) === true && $tokens[($stackPtr)]['code'] !== T_ELSE && $tokens[($stackPtr)]['code'] !== T_DO && $tokens[($stackPtr)]['code'] !== T_TRY ) { $found = 1; if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { $found = 0; } else if ($tokens[($stackPtr + 1)]['content'] !== ' ') { if (strpos($tokens[($stackPtr + 1)]['content'], $phpcsFile->eolChar) !== false) { $found = 'newline'; } else { $found = strlen($tokens[($stackPtr + 1)]['content']); } } if ($found !== 1) { $error = 'Expected 1 space after scope keyword "%s", found %s'; $data = array( strtoupper($tokens[$stackPtr]['content']), $found, ); $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterScopeKeyword', $data); if ($fix === true) { if ($found === 0) { $phpcsFile->fixer->addContent($stackPtr, ' '); } else { $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); } } } }//end if // Opening brace should be on a new line. if (isset($tokens[$stackPtr]['scope_opener']) === true) { $openingBracePtr = $tokens[$stackPtr]['scope_opener']; $braceLine = $tokens[$openingBracePtr]['line']; // If this is alternate syntax ":" instead of "{" then skip it. if (isset($tokens[$stackPtr]['scope_opener']) === true) { $openingBracePtr = $tokens[$stackPtr]['scope_opener']; if ($tokens[$openingBracePtr]['code'] === T_COLON) { return; } } if ($tokens[($stackPtr)]['code'] === T_ELSE || $tokens[($stackPtr)]['code'] === T_TRY || $tokens[($stackPtr)]['code'] === T_DO ) { $scopeLine = $tokens[$stackPtr]['line']; // Measure from the scope opener. $lineDifference = ($braceLine - $scopeLine); } else { $closerLine = $tokens[$tokens[$stackPtr]['parenthesis_closer']]['line']; // Measure from the scope closing parenthesis. $lineDifference = ($braceLine - $closerLine); } if ($lineDifference !== 1) { $data = array( $tokens[$openingBracePtr]['content'], $tokens[$stackPtr]['content'], ); if (isset($closerLine) === true) { $error = 'Opening brace "%s" should be on a new line after "%s (...)"'; } else { $error = 'Opening brace "%s" should be on a new line after the keyword "%s"'; } $fix = $phpcsFile->addFixableError($error, $openingBracePtr, 'ScopeOpeningBraceOnNewLine', $data); if ($fix === true) { $prevContentPtr = $phpcsFile->findPrevious(T_WHITESPACE, ($openingBracePtr - 1), null, true); $phpcsFile->fixer->beginChangeset(); for ($i = ($prevContentPtr + 1); $i < $openingBracePtr; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->addNewlineBefore($openingBracePtr); $phpcsFile->fixer->endChangeset(); } }//end if }//end if // No empty lines after opening brace. if (isset($tokens[$stackPtr]['scope_opener']) === true) { $openerPtr = $tokens[$stackPtr]['scope_opener']; $nextContentPtr = $phpcsFile->findNext(T_WHITESPACE, ($openerPtr + 1), null, true); $braceLine = $tokens[$openerPtr]['line']; $nextContentLine = $tokens[$nextContentPtr]['line']; $lineDifference = ($nextContentLine - $braceLine); if ($lineDifference === 0 || $lineDifference > 1) { $data = array($tokens[$openerPtr]['content']); $error = 'Expected content on line after "%s"'; $fix = $phpcsFile->addFixableError($error, $openerPtr, 'NewlineAfterOpeningBrace', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); for ($i = ($openerPtr + 1); $i < $nextContentPtr; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->addContent($openerPtr, $phpcsFile->eolChar); $phpcsFile->fixer->endChangeset(); } } }//end if // Closing brace should be on a new line. if (isset($tokens[$stackPtr]['scope_closer']) === true) { $closerPtr = $tokens[$stackPtr]['scope_closer']; $prevContentPtr = $phpcsFile->findPrevious(T_WHITESPACE, ($closerPtr - 1), null, true); $braceLine = $tokens[$closerPtr]['line']; $prevContentLine = $tokens[$prevContentPtr]['line']; $lineDifference = ($braceLine - $prevContentLine); if ($lineDifference !== 1) { $data = array($tokens[$closerPtr]['content']); $error = 'Closing brace "%s" should be on a new line'; $fix = $phpcsFile->addFixableError($error, $closerPtr, 'ClosingBraceOnNewLine', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); for ($i = ($prevContentPtr + 1); $i < $closerPtr; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->addNewlineBefore($closerPtr); $phpcsFile->fixer->endChangeset(); } } }//end if }
Processes this test, when one of its tokens is encountered. @param File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { if ($this->tabWidth === null) { if (isset($phpcsFile->config->tabWidth) === false || $phpcsFile->config->tabWidth === 0) { // We have no idea how wide tabs are, so assume 4 spaces for fixing. // It shouldn't really matter because alignment and spacing sniffs // elsewhere in the standard should fix things up. $this->tabWidth = 4; } else { $this->tabWidth = $phpcsFile->config->tabWidth; $this->indentUnit = 'tab'; } } $tokens = $phpcsFile->getTokens(); // First make sure all arrays use short array syntax, this makes fixing much easier. if ($tokens[$stackPtr]['code'] === T_ARRAY) { $error = 'Short array syntax must be used to define arrays'; $fix = $phpcsFile->addFixableError($error, $stackPtr, 'FoundLongArray'); if ($fix === true) { $tokens = $phpcsFile->getTokens(); $opener = $tokens[$stackPtr]['parenthesis_opener']; $closer = $tokens[$stackPtr]['parenthesis_closer']; $phpcsFile->fixer->beginChangeset(); if ($opener === null) { $phpcsFile->fixer->replaceToken($stackPtr, '[]'); } else { $phpcsFile->fixer->replaceToken($stackPtr, ''); $phpcsFile->fixer->replaceToken($opener, '['); $phpcsFile->fixer->replaceToken($closer, ']'); } $phpcsFile->fixer->endChangeset(); } }//end if if ($tokens[$stackPtr]['code'] === T_ARRAY) { $arrayStart = $tokens[$stackPtr]['parenthesis_opener']; if (isset($tokens[$arrayStart]['parenthesis_closer']) === false) { return; } $arrayEnd = $tokens[$arrayStart]['parenthesis_closer']; } else { $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'yes'); $arrayStart = $stackPtr; $arrayEnd = $tokens[$stackPtr]['bracket_closer']; }//end if // Check for empty arrays. $content = $phpcsFile->findNext(T_WHITESPACE, ($arrayStart + 1), ($arrayEnd + 1), true); if ($content === $arrayEnd) { // Empty array, but if the brackets aren't together, there's a problem. if (($arrayEnd - $arrayStart) !== 1) { $error = 'Empty array declaration must have no space between the parentheses'; $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceInEmptyArray'); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->endChangeset(); } } // We can return here because there is nothing else to check. All code // below can assume that the array is not empty. return; } if ($tokens[$arrayStart]['line'] === $tokens[$arrayEnd]['line']) { $this->processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd); } else { $this->processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd); } }
Processes this sniff, when one of its tokens is encountered. @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
public function processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd) { $tokens = $phpcsFile->getTokens(); // Check if there are multiple values. If so, then it has to be multiple lines // unless it is contained inside a function call or condition. $valueCount = 0; $commas = array(); for ($i = ($arrayStart + 1); $i < $arrayEnd; $i++) { // Skip bracketed statements, like function calls. if ($tokens[$i]['code'] === T_OPEN_PARENTHESIS) { $i = $tokens[$i]['parenthesis_closer']; continue; } if ($tokens[$i]['code'] === T_COMMA) { // Before counting this comma, make sure we are not // at the end of the array. $next = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), $arrayEnd, true); if ($next !== false) { $valueCount++; $commas[] = $i; } else { // There is a comma at the end of a single line array. $error = 'Comma not allowed after last value in single-line array declaration'; $fix = $phpcsFile->addFixableError($error, $i, 'CommaAfterLast'); if ($fix === true) { $phpcsFile->fixer->replaceToken($i, ''); } } } }//end for // Now check each of the double arrows (if any). $nextArrow = $arrayStart; while (($nextArrow = $phpcsFile->findNext(T_DOUBLE_ARROW, ($nextArrow + 1), $arrayEnd)) !== false) { if ($tokens[($nextArrow - 1)]['code'] !== T_WHITESPACE) { $content = $tokens[($nextArrow - 1)]['content']; $error = 'Expected 1 space between "%s" and double arrow; 0 found'; $data = array($content); $fix = $phpcsFile->addFixableError($error, $nextArrow, 'NoSpaceBeforeDoubleArrow', $data); if ($fix === true) { $phpcsFile->fixer->addContentBefore($nextArrow, ' '); } } else { $spaceLength = $tokens[($nextArrow - 1)]['length']; if ($spaceLength !== 1) { $content = $tokens[($nextArrow - 2)]['content']; $error = 'Expected 1 space between "%s" and double arrow; %s found'; $data = array( $content, $spaceLength, ); $fix = $phpcsFile->addFixableError($error, $nextArrow, 'SpaceBeforeDoubleArrow', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken(($nextArrow - 1), ' '); } } }//end if if ($tokens[($nextArrow + 1)]['code'] !== T_WHITESPACE) { $content = $tokens[($nextArrow + 1)]['content']; $error = 'Expected 1 space between double arrow and "%s"; 0 found'; $data = array($content); $fix = $phpcsFile->addFixableError($error, $nextArrow, 'NoSpaceAfterDoubleArrow', $data); if ($fix === true) { $phpcsFile->fixer->addContent($nextArrow, ' '); } } else { $spaceLength = $tokens[($nextArrow + 1)]['length']; if ($spaceLength !== 1) { $content = $tokens[($nextArrow + 2)]['content']; $error = 'Expected 1 space between double arrow and "%s"; %s found'; $data = array( $content, $spaceLength, ); $fix = $phpcsFile->addFixableError($error, $nextArrow, 'SpaceAfterDoubleArrow', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken(($nextArrow + 1), ' '); } } }//end if }//end while if ($valueCount > 0) { $conditionCheck = $phpcsFile->findPrevious(array(T_OPEN_PARENTHESIS, T_SEMICOLON), ($stackPtr - 1), null, false); if ($conditionCheck === false || $tokens[$conditionCheck]['line'] !== $tokens[$stackPtr]['line'] ) { $error = 'Array with multiple values cannot be declared on a single line'; $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SingleLineNotAllowed'); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $phpcsFile->fixer->addNewline($arrayStart); $phpcsFile->fixer->addNewlineBefore($arrayEnd); $phpcsFile->fixer->endChangeset(); } return; } // We have a multiple value array that is inside a condition or // function. Check its spacing is correct. foreach ($commas as $comma) { if ($tokens[($comma + 1)]['code'] !== T_WHITESPACE) { $content = $tokens[($comma + 1)]['content']; $error = 'Expected 1 space between comma and "%s"; 0 found'; $data = array($content); $fix = $phpcsFile->addFixableError($error, $comma, 'NoSpaceAfterComma', $data); if ($fix === true) { $phpcsFile->fixer->addContent($comma, ' '); } } else { $spaceLength = $tokens[($comma + 1)]['length']; if ($spaceLength !== 1) { $content = $tokens[($comma + 2)]['content']; $error = 'Expected 1 space between comma and "%s"; %s found'; $data = array( $content, $spaceLength, ); $fix = $phpcsFile->addFixableError($error, $comma, 'SpaceAfterComma', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken(($comma + 1), ' '); } } }//end if if ($tokens[($comma - 1)]['code'] === T_WHITESPACE) { $content = $tokens[($comma - 2)]['content']; $spaceLength = $tokens[($comma - 1)]['length']; $error = 'Expected 0 spaces between "%s" and comma; %s found'; $data = array( $content, $spaceLength, ); $fix = $phpcsFile->addFixableError($error, $comma, 'SpaceBeforeComma', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken(($comma - 1), ''); } } }//end foreach }//end if }
Processes a single-line array definition. @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. @param int $stackPtr The position of the current token in the stack passed in $tokens. @param int $arrayStart The token that starts the array definition. @param int $arrayEnd The token that ends the array definition. @return void
entailment
public function processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd) { $tokens = $phpcsFile->getTokens(); $keywordStart = $tokens[$stackPtr]['column']; $prevNonWhitespaceToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); // Find where this array should be indented from. switch ($tokens[$prevNonWhitespaceToken]['code']) { case T_EQUAL: case T_OPEN_PARENTHESIS: // It's "=", "(" or "return". $starts = array( T_VARIABLE, T_VAR, T_PUBLIC, T_PRIVATE, T_PROTECTED, T_ARRAY_CAST, T_UNSET_CAST, T_OBJECT_CAST, T_STATIC, T_CONST, T_RETURN, T_OBJECT_OPERATOR, ); $firstOnLine = $phpcsFile->findFirstOnLine($starts, $prevNonWhitespaceToken); $indentStart = $firstOnLine; break; case T_DOUBLE_ARROW: // It's an array in an array "=> []". $indentStart = $phpcsFile->findPrevious(T_WHITESPACE, ($prevNonWhitespaceToken - 1), null, true); break; case T_RETURN: $indentStart = $prevNonWhitespaceToken; break; case T_COMMENT: case T_OPEN_SHORT_ARRAY: // It's an array in an array "[[]]" or the end of an array line "[],". $indentStart = $stackPtr; break; case T_COMMA: // The end of an array line "[],". // Argument in a function "$item->save($data, [...], ...)". $starts = array( T_VARIABLE, T_VAR, T_PUBLIC, T_PRIVATE, T_PROTECTED, T_ARRAY_CAST, T_UNSET_CAST, T_OBJECT_CAST, T_STATIC, T_CONST, T_RETURN, T_OBJECT_OPERATOR, T_CLOSE_SHORT_ARRAY, T_CONSTANT_ENCAPSED_STRING, ); $firstOnLine = $phpcsFile->findFirstOnLine($starts, $prevNonWhitespaceToken); $indentStart = $firstOnLine; break; default: // Nothing expected preceded this so leave ptr where it is and // it should get picked in a future pass. $indentStart = $stackPtr; }//end switch // If this is the first argument in a function ensure the bracket to be right after the parenthesis. eg "array_combine([". if ($tokens[$prevNonWhitespaceToken]['code'] === T_OPEN_PARENTHESIS && $tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) { if ($tokens[$stackPtr]['line'] > $tokens[$prevNonWhitespaceToken]['line']) { $error = 'Array openening bracket should be after function open parenthesis "(["'; $data = array(); $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ShortArrayOpenWrongLine', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); for ($i = ($prevNonWhitespaceToken + 1); $i < $stackPtr; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->endChangeset(); } } } // Get content before closing array bracket/brace. $lastContent = $phpcsFile->findPrevious(T_WHITESPACE, ($arrayEnd - 1), $arrayStart, true); // Check for ) after last Array end. $afterCloser = $phpcsFile->findNext(T_WHITESPACE, ($arrayEnd + 1), null, true); if ($tokens[$afterCloser]['code'] === T_CLOSE_PARENTHESIS) { if ($tokens[$afterCloser]['column'] !== ($tokens[$arrayEnd]['column'] + 1)) { $error = 'Closing parenthesis should be after array closing bracket "])"'; $data = array(); $fix = $phpcsFile->addFixableError($error, $afterCloser, 'CloseBracketAfterArrayBracket'); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); for ($i = ($arrayEnd + 1); $i < $afterCloser; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->endChangeset(); } } } // Check the closing bracket is on a new line. if ($tokens[$lastContent]['line'] === $tokens[$arrayEnd]['line']) { $error = 'Closing parenthesis of array declaration must be on a new line'; $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseArrayBraceNewLine'); if ($fix === true) { $phpcsFile->fixer->addNewlineBefore($arrayEnd); } } else if ($tokens[$arrayEnd]['column'] !== $tokens[$indentStart]['column']) { // Check the closing bracket with the array declarer or if an // array in an array the previous array key. if ($tokens[$indentStart]['column'] > 1) { $expected = ($tokens[$indentStart]['column'] - 1); } else { $expected = $this->tabWidth; } $found = ($tokens[$arrayEnd]['column'] - 1); $error = 'Closing parenthesis not aligned correctly; expected %s %s but found %s'; $data = array( ($expected / $this->tabWidth), Common::pluralize($this->indentUnit, ($expected / $this->tabWidth)), ($found / $this->tabWidth), ); $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseArrayBraceNotAligned', $data); if ($fix === true) { if ($found === 0) { $phpcsFile->fixer->addContent(($arrayEnd - 1), str_repeat(' ', $expected)); } else { $phpcsFile->fixer->replaceToken(($arrayEnd - 1), str_repeat(' ', $expected)); } } }//end if $keyUsed = false; $singleUsed = false; $indices = array(); $maxLength = 0; if ($tokens[$stackPtr]['code'] === T_ARRAY) { $lastToken = $tokens[$stackPtr]['parenthesis_opener']; } else { $lastToken = $stackPtr; } // Find all the double arrows that reside in this scope. for ($nextToken = ($stackPtr + 1); $nextToken < $arrayEnd; $nextToken++) { // Skip bracketed statements, like function calls. if ($tokens[$nextToken]['code'] === T_OPEN_PARENTHESIS && (isset($tokens[$nextToken]['parenthesis_owner']) === false || $tokens[$nextToken]['parenthesis_owner'] !== $stackPtr) ) { $nextToken = $tokens[$nextToken]['parenthesis_closer']; continue; } if ($tokens[$nextToken]['code'] === T_ARRAY || $tokens[$nextToken]['code'] === T_OPEN_SHORT_ARRAY || $tokens[$nextToken]['code'] === T_CLOSURE ) { // Let subsequent calls of this test handle nested arrays. if ($tokens[$lastToken]['code'] !== T_DOUBLE_ARROW) { $indices[] = array('value' => $nextToken); $lastToken = $nextToken; } if ($tokens[$nextToken]['code'] === T_ARRAY) { $nextToken = $tokens[$tokens[$nextToken]['parenthesis_opener']]['parenthesis_closer']; } else if ($tokens[$nextToken]['code'] === T_OPEN_SHORT_ARRAY) { $nextToken = $tokens[$nextToken]['bracket_closer']; } else { $nextToken = $tokens[$nextToken]['scope_closer']; } $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextToken + 1), null, true); if ($tokens[$nextToken]['code'] !== T_COMMA) { $nextToken--; } else { $lastToken = $nextToken; } continue; }//end if if ($tokens[$nextToken]['code'] !== T_DOUBLE_ARROW && $tokens[$nextToken]['code'] !== T_COMMA ) { continue; } $currentEntry = array(); if ($tokens[$nextToken]['code'] === T_COMMA) { $stackPtrCount = 0; if (isset($tokens[$stackPtr]['nested_parenthesis']) === true) { $stackPtrCount = count($tokens[$stackPtr]['nested_parenthesis']); } $commaCount = 0; if (isset($tokens[$nextToken]['nested_parenthesis']) === true) { $commaCount = count($tokens[$nextToken]['nested_parenthesis']); if ($tokens[$stackPtr]['code'] === T_ARRAY) { // Remove parenthesis that are used to define the array. $commaCount--; } } if ($commaCount > $stackPtrCount) { // This comma is inside more parenthesis than the ARRAY keyword, // then there it is actually a comma used to separate arguments // in a function call. continue; } if ($keyUsed === true && $tokens[$lastToken]['code'] === T_COMMA) { $error = 'No key specified for array entry; first entry specifies key'; $phpcsFile->addError($error, $nextToken, 'NoKeySpecified'); return; } if ($keyUsed === false) { if ($tokens[($nextToken - 1)]['code'] === T_WHITESPACE) { $content = $tokens[($nextToken - 2)]['content']; if ($tokens[($nextToken - 1)]['content'] === $phpcsFile->eolChar) { $spaceLength = 'newline'; } else { $spaceLength = $tokens[($nextToken - 1)]['length']; } $error = 'Expected 0 spaces between "%s" and comma; %s found'; $data = array( $content, $spaceLength, ); $fix = $phpcsFile->addFixableError($error, $nextToken, 'SpaceBeforeComma', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken(($nextToken - 1), ''); } } $valueContent = $phpcsFile->findNext( Tokens::$emptyTokens, ($lastToken + 1), $nextToken, true ); $indices[] = array('value' => $valueContent); $singleUsed = true; }//end if $lastToken = $nextToken; continue; }//end if if ($tokens[$nextToken]['code'] === T_DOUBLE_ARROW) { if ($singleUsed === true) { $error = 'Key specified for array entry; first entry has no key'; $phpcsFile->addError($error, $nextToken, 'KeySpecified'); return; } $currentEntry['arrow'] = $nextToken; $keyUsed = true; // Find the start of index that uses this double arrow. $indexEnd = $phpcsFile->findPrevious(T_WHITESPACE, ($nextToken - 1), $arrayStart, true); $indexStart = $phpcsFile->findStartOfStatement($indexEnd); if ($indexStart === $indexEnd) { $currentEntry['index'] = $indexEnd; $currentEntry['index_content'] = $tokens[$indexEnd]['content']; } else { $currentEntry['index'] = $indexStart; $currentEntry['index_content'] = $phpcsFile->getTokensAsString($indexStart, ($indexEnd - $indexStart + 1)); } $indexLength = mb_strlen($currentEntry['index_content']); if ($maxLength < $indexLength) { $maxLength = $indexLength; } // Find the value of this index. $nextContent = $phpcsFile->findNext( Tokens::$emptyTokens, ($nextToken + 1), $arrayEnd, true ); if ($nextContent === false) { break; } $currentEntry['value'] = $nextContent; $indices[] = $currentEntry; $lastToken = $nextToken; }//end if }//end for /* This section checks for arrays that don't specify keys. Arrays such as: array( 'aaa', 'bbb', 'd', ); */ if ($keyUsed === false && empty($indices) === false) { $count = count($indices); $lastIndex = $indices[($count - 1)]['value']; $trailingContent = $phpcsFile->findPrevious( Tokens::$emptyTokens, ($arrayEnd - 1), $lastIndex, true ); if ($tokens[$trailingContent]['code'] !== T_COMMA) { $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'no'); $error = 'Comma required after last value in array declaration'; $fix = $phpcsFile->addFixableError($error, $trailingContent, 'NoCommaAfterLast'); if ($fix === true) { $phpcsFile->fixer->addContent($trailingContent, ','); } } else { $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'yes'); } $lastValueLine = false; foreach ($indices as $value) { if (empty($value['value']) === true) { // Array was malformed and we couldn't figure out // the array value correctly, so we have to ignore it. // Other parts of this sniff will correct the error. continue; } if ($lastValueLine !== false && $tokens[$value['value']]['line'] === $lastValueLine) { $error = 'Each value in a multi-line array must be on a new line'; $fix = $phpcsFile->addFixableError($error, $value['value'], 'ValueNoNewline'); if ($fix === true) { if ($tokens[($value['value'] - 1)]['code'] === T_WHITESPACE) { $phpcsFile->fixer->replaceToken(($value['value'] - 1), ''); } $phpcsFile->fixer->addNewlineBefore($value['value']); } } else if ($tokens[($value['value'] - 1)]['code'] === T_WHITESPACE) { // Expected indent. if ($tokens[$indentStart]['column'] > 1) { $expected = ($tokens[$indentStart]['column'] + $this->tabWidth - 1); } else { $expected = $this->tabWidth; } $first = $phpcsFile->findFirstOnLine(T_WHITESPACE, $value['value'], true); $found = ($tokens[$first]['column'] - 1); if ($found !== $expected) { $error = 'Array value not aligned correctly; expected %s %s but found %s'; $data = array( ($expected / $this->tabWidth), Common::pluralize($this->indentUnit, ($expected / $this->tabWidth)), ($found / $this->tabWidth), ); $fix = $phpcsFile->addFixableError($error, $value['value'], 'ValueNotAligned', $data); if ($fix === true) { if ($found === 0) { $phpcsFile->fixer->addContent(($value['value'] - 1), str_repeat(' ', $expected)); } else { $phpcsFile->fixer->replaceToken(($value['value'] - 1), str_repeat(' ', $expected)); } } } }//end if $lastValueLine = $tokens[$value['value']]['line']; }//end foreach }//end if /* Below the actual indentation of the array is checked. Errors will be thrown when a key is not aligned, when a double arrow is not aligned, and when a value is not aligned correctly. If an error is found in one of the above areas, then errors are not reported for the rest of the line to avoid reporting spaces and columns incorrectly. Often fixing the first problem will fix the other 2 anyway. For example: $a = array( 'index' => '2', ); or $a = [ 'index' => '2', ]; In this array, the double arrow is indented too far, but this will also cause an error in the value's alignment. If the arrow were to be moved back one space however, then both errors would be fixed. */ $numValues = count($indices); // Expected indent. if ($tokens[$indentStart]['column'] > 1) { $indicesStart = ($tokens[$indentStart]['column'] + $this->tabWidth); } else { $indicesStart = $this->tabWidth; } $arrowStart = ($indicesStart + $maxLength + 1); $valueStart = ($arrowStart + 3); $indexLine = $tokens[$stackPtr]['line']; $lastIndexLine = null; foreach ($indices as $index) { if (isset($index['index']) === false) { // Array value only. if ($tokens[$index['value']]['line'] === $tokens[$stackPtr]['line'] && $numValues > 1) { $error = 'The first value in a multi-value array must be on a new line'; $fix = $phpcsFile->addFixableError($error, $stackPtr, 'FirstValueNoNewline'); if ($fix === true) { $phpcsFile->fixer->addNewlineBefore($index['value']); } } continue; } $lastIndexLine = $indexLine; $indexLine = $tokens[$index['index']]['line']; if ($indexLine === $tokens[$stackPtr]['line']) { $error = 'The first index in a multi-value array must be on a new line'; $fix = $phpcsFile->addFixableError($error, $index['index'], 'FirstIndexNoNewline'); if ($fix === true) { $phpcsFile->fixer->addNewlineBefore($index['index']); } continue; } if ($indexLine === $lastIndexLine) { $error = 'Each index in a multi-line array must be on a new line'; $fix = $phpcsFile->addFixableError($error, $index['index'], 'IndexNoNewline'); if ($fix === true) { if ($tokens[($index['index'] - 1)]['code'] === T_WHITESPACE) { $phpcsFile->fixer->replaceToken(($index['index'] - 1), ''); } $phpcsFile->fixer->addNewlineBefore($index['index']); } continue; } if ($tokens[$index['index']]['column'] !== $indicesStart) { $expected = ($indicesStart - 1); $found = ($tokens[$index['index']]['column'] - 1); $error = 'Array key not aligned correctly; expected %s %s but found %s'; $data = array( ($expected / $this->tabWidth), Common::pluralize($this->indentUnit, ($expected / $this->tabWidth)), ($found / $this->tabWidth), ); $fix = $phpcsFile->addFixableError($error, $index['index'], 'KeyNotAligned', $data); if ($fix === true) { if ($found === 0) { $phpcsFile->fixer->addContent(($index['index'] - 1), str_repeat(' ', $expected)); } else { $phpcsFile->fixer->replaceToken(($index['index'] - 1), str_repeat(' ', $expected)); } } continue; }//end if if ($tokens[$index['arrow']]['column'] !== $arrowStart) { $expected = ($arrowStart - (mb_strlen($index['index_content']) + $tokens[$index['index']]['column'])); $found = ($tokens[$index['arrow']]['column'] - (mb_strlen($index['index_content']) + $tokens[$index['index']]['column'])); $error = 'Array double arrow not aligned correctly; expected %s %s but found %s'; $data = array( $expected, Common::pluralize('space', $expected), $found, ); $fix = $phpcsFile->addFixableError($error, $index['arrow'], 'DoubleArrowNotAligned', $data); if ($fix === true) { if ($found === 0) { $phpcsFile->fixer->addContent(($index['arrow'] - 1), str_repeat(' ', $expected)); } else { $phpcsFile->fixer->replaceToken(($index['arrow'] - 1), str_repeat(' ', $expected)); } } continue; }//end if if ($tokens[$index['value']]['column'] !== $valueStart) { $expected = ($valueStart - ($tokens[$index['arrow']]['length'] + $tokens[$index['arrow']]['column'])); $found = ($tokens[$index['value']]['column'] - ($tokens[$index['arrow']]['length'] + $tokens[$index['arrow']]['column'])); if ($found < 0) { $found = 'newline'; } $error = 'Array value not aligned correctly; expected %s %s but found %s'; $data = array( $expected, Common::pluralize('space', $expected), $found, ); $fix = $phpcsFile->addFixableError($error, $index['arrow'], 'ValueNotAligned', $data); if ($fix === true) { if ($found === 'newline') { $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($index['value'] - 1), null, true); $phpcsFile->fixer->beginChangeset(); for ($i = ($prev + 1); $i < $index['value']; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->replaceToken(($index['value'] - 1), str_repeat(' ', $expected)); $phpcsFile->fixer->endChangeset(); } else if ($found === 0) { $phpcsFile->fixer->addContent(($index['value'] - 1), str_repeat(' ', $expected)); } else { $phpcsFile->fixer->replaceToken(($index['value'] - 1), str_repeat(' ', $expected)); } } }//end if // Check each line ends in a comma. $valueLine = $tokens[$index['value']]['line']; $nextComma = false; for ($i = $index['value']; $i < $arrayEnd; $i++) { // Skip bracketed statements, like function calls. if ($tokens[$i]['code'] === T_OPEN_PARENTHESIS) { $i = $tokens[$i]['parenthesis_closer']; $valueLine = $tokens[$i]['line']; continue; } if ($tokens[$i]['code'] === T_ARRAY) { $i = $tokens[$tokens[$i]['parenthesis_opener']]['parenthesis_closer']; $valueLine = $tokens[$i]['line']; continue; } // Skip to the end of multi-line strings. if (isset(Tokens::$stringTokens[$tokens[$i]['code']]) === true) { $i = $phpcsFile->findNext($tokens[$i]['code'], ($i + 1), null, true); $i--; $valueLine = $tokens[$i]['line']; continue; } if ($tokens[$i]['code'] === T_OPEN_SHORT_ARRAY) { $i = $tokens[$i]['bracket_closer']; $valueLine = $tokens[$i]['line']; continue; } if ($tokens[$i]['code'] === T_CLOSURE) { $i = $tokens[$i]['scope_closer']; $valueLine = $tokens[$i]['line']; continue; } if ($tokens[$i]['code'] === T_COMMA) { $nextComma = $i; break; } }//end for if ($nextComma === false || ($tokens[$nextComma]['line'] !== $valueLine)) { $error = 'Each line in an array declaration must end in a comma'; $fix = $phpcsFile->addFixableError($error, $index['value'], 'NoComma'); if ($fix === true) { // Find the end of the line and put a comma there. for ($i = ($index['value'] + 1); $i < $arrayEnd; $i++) { if ($tokens[$i]['line'] > $valueLine) { break; } } $phpcsFile->fixer->addContentBefore(($i - 1), ','); } }//end if // Check that there is no space before the comma. if ($nextComma !== false && $tokens[($nextComma - 1)]['code'] === T_WHITESPACE) { $content = $tokens[($nextComma - 2)]['content']; $spaceLength = $tokens[($nextComma - 1)]['length']; $error = 'Expected 0 spaces between "%s" and comma; %s found'; $data = array( $content, $spaceLength, ); $fix = $phpcsFile->addFixableError($error, $nextComma, 'SpaceBeforeComma', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken(($nextComma - 1), ''); } } }//end foreach }
Processes a multi-line array definition. @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. @param int $stackPtr The position of the current token in the stack passed in $tokens. @param int $arrayStart The token that starts the array definition. @param int $arrayEnd The token that ends the array definition. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if (isset($tokens[$stackPtr]['parenthesis_opener']) === false || isset($tokens[$stackPtr]['parenthesis_closer']) === false || $tokens[$stackPtr]['parenthesis_opener'] === null || $tokens[$stackPtr]['parenthesis_closer'] === null ) { return; } $openBracket = $tokens[$stackPtr]['parenthesis_opener']; $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; if (strtolower($tokens[$stackPtr]['content']) === 'function') { // Must be one space after the FUNCTION keyword. if ($tokens[($stackPtr + 1)]['content'] === $phpcsFile->eolChar) { $spaces = 'newline'; } else if ($tokens[($stackPtr + 1)]['code'] === T_WHITESPACE) { $spaces = strlen($tokens[($stackPtr + 1)]['content']); } else { $spaces = 0; } if ($spaces !== 1) { $error = 'Expected 1 space after FUNCTION keyword; %s found'; $data = array($spaces); $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceAfterFunction', $data); if ($fix === true) { if ($spaces === 0) { $phpcsFile->fixer->addContent($stackPtr, ' '); } else { $phpcsFile->fixer->replaceToken(($stackPtr + 1), ' '); } } } }//end if // Must be one space before the opening parenthesis. For closures, this is // enforced by the first check because there is no content between the keywords // and the opening parenthesis. if ($tokens[$stackPtr]['code'] === T_FUNCTION) { if ($tokens[($openBracket - 1)]['content'] === $phpcsFile->eolChar) { $spaces = 'newline'; } else if ($tokens[($openBracket - 1)]['code'] === T_WHITESPACE) { $spaces = strlen($tokens[($openBracket - 1)]['content']); } else { $spaces = 0; } if ($spaces !== 0) { $error = 'Expected 0 spaces before opening parenthesis; %s found'; $data = array($spaces); $fix = $phpcsFile->addFixableError($error, $openBracket, 'SpaceBeforeOpenParenthesis', $data); if ($fix === true) { $phpcsFile->fixer->replaceToken(($openBracket - 1), ''); } } }//end if // Must be one space before and after USE keyword for closures. if ($tokens[$stackPtr]['code'] === T_CLOSURE) { $use = $phpcsFile->findNext(T_USE, ($closeBracket + 1), $tokens[$stackPtr]['scope_opener']); if ($use !== false) { if ($tokens[($use + 1)]['code'] !== T_WHITESPACE) { $length = 0; } else if ($tokens[($use + 1)]['content'] === "\t") { $length = '\t'; } else { $length = strlen($tokens[($use + 1)]['content']); } if ($length !== 1) { $error = 'Expected 1 space after USE keyword; found %s'; $data = array($length); $fix = $phpcsFile->addFixableError($error, $use, 'SpaceAfterUse', $data); if ($fix === true) { if ($length === 0) { $phpcsFile->fixer->addContent($use, ' '); } else { $phpcsFile->fixer->replaceToken(($use + 1), ' '); } } } if ($tokens[($use - 1)]['code'] !== T_WHITESPACE) { $length = 0; } else if ($tokens[($use - 1)]['content'] === "\t") { $length = '\t'; } else { $length = strlen($tokens[($use - 1)]['content']); } if ($length !== 1) { $error = 'Expected 1 space before USE keyword; found %s'; $data = array($length); $fix = $phpcsFile->addFixableError($error, $use, 'SpaceBeforeUse', $data); if ($fix === true) { if ($length === 0) { $phpcsFile->fixer->addContentBefore($use, ' '); } else { $phpcsFile->fixer->replaceToken(($use - 1), ' '); } } } }//end if }//end if if ($this->isMultiLineDeclaration($phpcsFile, $stackPtr, $openBracket, $tokens) === true) { $this->processMultiLineDeclaration($phpcsFile, $stackPtr, $tokens); } else { $this->processSingleLineDeclaration($phpcsFile, $stackPtr, $tokens); } }
Processes this test, when one of its tokens is encountered. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
public function isMultiLineDeclaration($phpcsFile, $stackPtr, $openBracket, $tokens) { $bracketsToCheck = array($stackPtr => $openBracket); // Closures may use the USE keyword and so be multi-line in this way. if ($tokens[$stackPtr]['code'] === T_CLOSURE) { $use = $phpcsFile->findNext(T_USE, ($tokens[$openBracket]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']); if ($use !== false) { $open = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1)); if ($open !== false) { $bracketsToCheck[$use] = $open; } } } foreach ($bracketsToCheck as $stackPtr => $openBracket) { // If the first argument is on a new line, this is a multi-line // function declaration, even if there is only one argument. $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($openBracket + 1), null, true); if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { return true; } $closeBracket = $tokens[$openBracket]['parenthesis_closer']; $end = $phpcsFile->findEndOfStatement($openBracket + 1); while ($tokens[$end]['code'] === T_COMMA) { // If the next bit of code is not on the same line, this is a // multi-line function declaration. $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), $closeBracket, true); if ($next === false) { continue(2); } if ($tokens[$next]['line'] !== $tokens[$end]['line']) { return true; } $end = $phpcsFile->findEndOfStatement($next); } // We've reached the last argument, so see if the next content // (should be the close bracket) is also on the same line. $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), $closeBracket, true); if ($next !== false && $tokens[$next]['line'] !== $tokens[$end]['line']) { return true; } }//end foreach return false; }
Determine if this is a multi-line function declaration. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @param int $openBracket The position of the opening bracket in the stack passed in $tokens. @param array $tokens The stack of tokens that make up the file. @return void
entailment
public function processSingleLineDeclaration($phpcsFile, $stackPtr, $tokens) { if ($tokens[$stackPtr]['code'] === T_CLOSURE) { $sniff = new OpeningFunctionBraceKernighanRitchieSniff(); } else { $sniff = new OpeningFunctionBraceBsdAllmanSniff(); } $sniff->checkClosures = true; $sniff->process($phpcsFile, $stackPtr); }
Processes single-line declarations. Just uses the Generic BSD-Allman brace sniff. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @param array $tokens The stack of tokens that make up the file. @return void
entailment
public function processMultiLineDeclaration($phpcsFile, $stackPtr, $tokens) { // We need to work out how far indented the function // declaration itself is, so we can work out how far to // indent parameters. $functionIndent = 0; for ($i = ($stackPtr - 1); $i >= 0; $i--) { if ($tokens[$i]['line'] !== $tokens[$stackPtr]['line']) { $i++; break; } } if ($tokens[$i]['code'] === T_WHITESPACE) { $functionIndent = strlen($tokens[$i]['content']); } // The closing parenthesis must be on a new line, even // when checking abstract function definitions. $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; $prev = $phpcsFile->findPrevious( T_WHITESPACE, ($closeBracket - 1), null, true ); if ($tokens[$closeBracket]['line'] !== $tokens[$tokens[$closeBracket]['parenthesis_opener']]['line']) { if ($tokens[$prev]['line'] === $tokens[$closeBracket]['line']) { $error = 'The closing parenthesis of a multi-line function declaration must be on a new line'; $fix = $phpcsFile->addFixableError($error, $closeBracket, 'CloseBracketLine'); if ($fix === true) { $phpcsFile->fixer->addNewlineBefore($closeBracket); } } } // If this is a closure and is using a USE statement, the closing // parenthesis we need to look at from now on is the closing parenthesis // of the USE statement. if ($tokens[$stackPtr]['code'] === T_CLOSURE) { $use = $phpcsFile->findNext(T_USE, ($closeBracket + 1), $tokens[$stackPtr]['scope_opener']); if ($use !== false) { $open = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1)); $closeBracket = $tokens[$open]['parenthesis_closer']; $prev = $phpcsFile->findPrevious( T_WHITESPACE, ($closeBracket - 1), null, true ); if ($tokens[$closeBracket]['line'] !== $tokens[$tokens[$closeBracket]['parenthesis_opener']]['line']) { if ($tokens[$prev]['line'] === $tokens[$closeBracket]['line']) { $error = 'The closing parenthesis of a multi-line use declaration must be on a new line'; $fix = $phpcsFile->addFixableError($error, $closeBracket, 'UseCloseBracketLine'); if ($fix === true) { $phpcsFile->fixer->addNewlineBefore($closeBracket); } } } }//end if }//end if // Each line between the parenthesis should be indented 4 spaces. $openBracket = $tokens[$stackPtr]['parenthesis_opener']; $lastLine = $tokens[$openBracket]['line']; for ($i = ($openBracket + 1); $i < $closeBracket; $i++) { if ($tokens[$i]['line'] !== $lastLine) { if ($i === $tokens[$stackPtr]['parenthesis_closer'] || ($tokens[$i]['code'] === T_WHITESPACE && (($i + 1) === $closeBracket || ($i + 1) === $tokens[$stackPtr]['parenthesis_closer'])) ) { // Closing braces need to be indented to the same level // as the function. $expectedIndent = $functionIndent; } else { $expectedIndent = ($functionIndent + $this->indent); } // We changed lines, so this should be a whitespace indent token. if ($tokens[$i]['code'] !== T_WHITESPACE) { $foundIndent = 0; } else if ($tokens[$i]['line'] !== $tokens[($i + 1)]['line']) { // This is an empty line, so don't check the indent. $foundIndent = $expectedIndent; $error = 'Blank lines are not allowed in a multi-line function declaration'; $fix = $phpcsFile->addFixableError($error, $i, 'EmptyLine'); if ($fix === true) { $phpcsFile->fixer->replaceToken($i, ''); } } else { $foundIndent = strlen($tokens[$i]['content']); } if ($expectedIndent !== $foundIndent) { $error = 'Multi-line function declaration not indented correctly; expected %s spaces but found %s'; $data = array( $expectedIndent, $foundIndent, ); $fix = $phpcsFile->addFixableError($error, $i, 'Indent', $data); if ($fix === true) { $spaces = str_repeat(' ', $expectedIndent); if ($foundIndent === 0) { $phpcsFile->fixer->addContentBefore($i, $spaces); } else { $phpcsFile->fixer->replaceToken($i, $spaces); } } } $lastLine = $tokens[$i]['line']; }//end if if ($tokens[$i]['code'] === T_ARRAY || $tokens[$i]['code'] === T_OPEN_SHORT_ARRAY) { // Skip arrays as they have their own indentation rules. if ($tokens[$i]['code'] === T_OPEN_SHORT_ARRAY) { $i = $tokens[$i]['bracket_closer']; } else { $i = $tokens[$i]['parenthesis_closer']; } $lastLine = $tokens[$i]['line']; continue; } }//end for if (isset($tokens[$stackPtr]['scope_opener']) === false) { return; } $openBracket = $tokens[$stackPtr]['parenthesis_opener']; $this->processBracket($phpcsFile, $openBracket, $tokens, 'function'); if ($tokens[$stackPtr]['code'] !== T_CLOSURE) { return; } $use = $phpcsFile->findNext(T_USE, ($tokens[$stackPtr]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']); if ($use === false) { return; } $openBracket = $phpcsFile->findNext(T_OPEN_PARENTHESIS, ($use + 1), null); $this->processBracket($phpcsFile, $openBracket, $tokens, 'use'); // Also check spacing. if ($tokens[($use - 1)]['code'] === T_WHITESPACE) { $gap = strlen($tokens[($use - 1)]['content']); } else { $gap = 0; } }
Processes multi-line declarations. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @param array $tokens The stack of tokens that make up the file. @return void
entailment
public function processBracket($phpcsFile, $openBracket, $tokens, $type='function') { $errorPrefix = ''; if ($type === 'use') { $errorPrefix = 'Use'; } $closeBracket = $tokens[$openBracket]['parenthesis_closer']; // The open bracket should be the last thing on the line. if ($tokens[$openBracket]['line'] !== $tokens[$closeBracket]['line']) { $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($openBracket + 1), null, true); if ($tokens[$next]['line'] !== ($tokens[$openBracket]['line'] + 1)) { $error = 'The first parameter of a multi-line '.$type.' declaration must be on the line after the opening bracket'; $fix = $phpcsFile->addFixableError($error, $next, $errorPrefix.'FirstParamSpacing'); if ($fix === true) { $phpcsFile->fixer->addNewline($openBracket); } } } // Each line between the brackets should contain a single parameter. $lastComma = null; for ($i = ($openBracket + 1); $i < $closeBracket; $i++) { // Skip brackets, like arrays, as they can contain commas. if (isset($tokens[$i]['bracket_opener']) === true) { $i = $tokens[$i]['bracket_closer']; continue; } if (isset($tokens[$i]['parenthesis_opener']) === true) { $i = $tokens[$i]['parenthesis_closer']; continue; } if ($tokens[$i]['code'] !== T_COMMA) { continue; } $next = $phpcsFile->findNext(T_WHITESPACE, ($i + 1), null, true); if ($tokens[$next]['line'] === $tokens[$i]['line']) { $error = 'Multi-line '.$type.' declarations must define one parameter per line'; $fix = $phpcsFile->addFixableError($error, $next, $errorPrefix.'OneParamPerLine'); if ($fix === true) { $phpcsFile->fixer->addNewline($i); } } }//end for }
Processes the contents of a single set of brackets. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $openBracket The position of the open bracket in the stack passed in $tokens. @param array $tokens The stack of tokens that make up the file. @param string $type The type of the token the brackets belong to (function or use). @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $fileName = basename($phpcsFile->getFilename()); if (strpos($fileName, '_helper.php') === false) { return; } else { // Check the filename. $expectedFilename = preg_replace('/_{2,}/', '_', strtolower($fileName)); if ($fileName !== $expectedFilename && $this->badFilename === false) { $data = array( $fileName, $expectedFilename, ); $error = 'Helper filename "%s" doesn\'t match the expected filename "%s"'; $phpcsFile->addError($error, 1, 'HelperBadFilename', $data); $this->badFilename = true; } // Check for class, interface, trait etc. $tokens = $phpcsFile->getTokens(); if (in_array($tokens[$stackPtr]['code'], $this->unwantedTokens) === true) { $error = 'Helper files must only contain functions'; $phpcsFile->addError($error, $stackPtr, 'HelperOnlyFunctions'); } }//end if }
Processes this sniff, when one of its tokens is encountered. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
public static function isLowerSnakeCase($string) { if (strcmp($string, strtolower($string)) !== 0) { return false; } if (strpos($string, ' ') !== false) { return false; } return true; }
Is lower snake case @param string $string The string to verify. @return boolean
entailment
public function process(File $phpcsFile, $stackPtr) { if ($this->tabWidth === null) { if (isset($phpcsFile->config->tabWidth) === false || $phpcsFile->config->tabWidth === 0) { // We have no idea how wide tabs are, so assume 4 spaces for fixing. // It shouldn't really matter because alignment and spacing sniffs // elsewhere in the standard should fix things up. $this->tabWidth = 4; } else { $this->tabWidth = $phpcsFile->config->tabWidth; } } $checkTokens = array( T_WHITESPACE => true, T_INLINE_HTML => true, T_DOC_COMMENT_WHITESPACE => true, ); $tokens = $phpcsFile->getTokens(); for ($i = ($stackPtr); $i < $phpcsFile->numTokens; $i++) { // Skip whitespace at the start of a new line and tokens not consdered white space. if ($tokens[$i]['column'] === 1 || isset($checkTokens[$tokens[$i]['code']]) === false) { continue; } // If tabs are being converted to spaces by the tokeniser, the // original content should be checked instead of the converted content. if (isset($tokens[$i]['orig_content']) === true) { $content = $tokens[$i]['orig_content']; } else { $content = $tokens[$i]['content']; } if (strpos($content, "\t") !== false) { // Try to maintain intended alignment by counting tabs and spaces. $countTabs = substr_count($content, "\t"); $countSpaces = substr_count($content, " "); if ($countTabs === 1) { $tabsPlural = ''; } else { $tabsPlural = 's'; } if ($countSpaces === 1) { $spacesPlural = ''; } else { $spacesPlural = 's'; } $data = array( $countTabs, $tabsPlural, $countSpaces, $spacesPlural, ); $error = 'Spaces must be used for alignment; %s tab%s and %s space%s found'; // The fix might make some lines misaligned if the tab didn't fill the number // of 'tabWidth' spaces, other alignment and spacing sniffs should fix that. $fix = $phpcsFile->addFixableError($error, $i, 'TabsUsedInAlignment', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $spaces = str_repeat(' ', (($this->tabWidth * $countTabs) + $countSpaces)); $phpcsFile->fixer->replaceToken($i, $spaces); $phpcsFile->fixer->endChangeset(); }//end if }//end if }//end for // Ignore the rest of the file. return ($phpcsFile->numTokens + 1); }
Processes this test, when one of its tokens is encountered. @param \PHP_CodeSniffer\Files\File $phpcsFile All the tokens found in the document. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) { $functionName = $phpcsFile->getDeclarationName($stackPtr); if ($functionName === null) { return; } // Is this a magic function. i.e., it is prefixed with "__"? if (preg_match('|^__[^_]|', $functionName) !== 0) { $magicPart = strtolower(substr($functionName, 2)); if (isset(Common::$magicMethods[$magicPart]) === false) { $errorData = array($functionName); $error = 'Function name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; $phpcsFile->addError($error, $stackPtr, 'FunctionDoubleUnderscore', $errorData); } return; } if (Common::isLowerSnakeCase($functionName) === false || $functionName !== strtolower($functionName) ) { $errorData = array($functionName); $error = 'Function "%s" must be snake_case'; $phpcsFile->addError($error, $stackPtr, 'FunctionNotSnakeCase', $errorData); } $warningLimit = 50; if (strlen($functionName) > $warningLimit) { $errorData = array( $functionName, $warningLimit, ); $warning = 'Function "%s" is over "%s" chars'; $phpcsFile->addWarning($warning, $stackPtr, 'FunctionNameIsLong', $errorData); } }
Processes the tokens outside the scope. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. @param int $stackPtr The position where this token was found. @return void
entailment
protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) { $methodName = $phpcsFile->getDeclarationName($stackPtr); if ($methodName === null) { // Ignore closures. return; } $className = $phpcsFile->getDeclarationName($currScope); // Is this a magic method. i.e., is prefixed with "__"? if (preg_match('|^__[^_]|', $methodName) !== 0) { $magicPart = strtolower(substr($methodName, 2)); if (isset(Common::$magicMethods[$magicPart]) === false) { $errorData = array($className.'::'.$methodName); $error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; $phpcsFile->addError($error, $stackPtr, 'MethodDoubleUnderscore', $errorData); } return; } // Get the method name without underscore prefix if it exists. if (strrpos($methodName, '_') === 0) { $namePart = substr($methodName, 1); } else { $namePart = $methodName; } // Naming check. if (Common::isCamelCaps($namePart, false, true, false) === false) { $errorData = array($methodName); $error = 'Method "%s" must be lowerCamelCase'; $phpcsFile->addError($error, $stackPtr, 'MethodNotLowerCamelCase', $errorData); } // Methods must not be prefixed with an underscore except those in publicMethodNames. if (strrpos($methodName, '_') === 0) { if (isset(Common::$publicMethodNames[$methodName]) === false) { $methodProps = $phpcsFile->getMethodProperties($stackPtr); $scope = $methodProps['scope']; $errorData = array($className.'::'.$methodName); $error = ucfirst($scope).' method "%s" must not be prefixed with an underscore'; $phpcsFile->addError($error, $stackPtr, 'MethodMustNotHaveUnderscore', $errorData); } } // Warn if method name is over 50 chars. $warningLimit = 50; if (strlen($methodName) > $warningLimit) { $errorData = array( $methodName, $warningLimit, ); $warning = 'Method "%s" is over "%s" chars'; $phpcsFile->addWarning($warning, $stackPtr, 'MethodNameIsLong', $errorData); } }
Processes the tokens within the scope. @param File $phpcsFile The file being processed. @param int $stackPtr The position where this token was found. @param int $currScope The position of the current scope. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $nextClass = $phpcsFile->findNext($this->register(), ($stackPtr + 1)); $fileName = basename($phpcsFile->getFilename()); if ($nextClass !== false) { if (in_array($fileName, $this->filesAllowedMultiClass) === false) { $error = 'Only one class is allowed in a file'; $phpcsFile->addError($error, $nextClass, 'MultipleFound'); } } }
Processes this sniff, when one of its tokens is encountered. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); // Find the next non whitespace token. $commentStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); // Allow namespace at top of file. if ($tokens[$commentStart]['code'] === T_NAMESPACE) { $semicolon = $phpcsFile->findNext(T_SEMICOLON, ($commentStart + 1)); $commentStart = $phpcsFile->findNext(T_WHITESPACE, ($semicolon + 1), null, true); } // Ignore vim header. if ($tokens[$commentStart]['code'] === T_COMMENT) { if (strstr($tokens[$commentStart]['content'], 'vim:') !== false) { $commentStart = $phpcsFile->findNext( T_WHITESPACE, ($commentStart + 1), null, true ); } } $errorToken = ($stackPtr + 1); if (isset($tokens[$errorToken]) === false) { $errorToken--; } if ($tokens[$commentStart]['code'] === T_CLOSE_TAG) { // We are only interested if this is the first open tag. return ($phpcsFile->numTokens + 1); } else if ($tokens[$commentStart]['code'] === T_COMMENT) { $error = 'You must use "/**" style comments for a file comment'; $phpcsFile->addError($error, $errorToken, 'WrongStyle'); $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'yes'); return ($phpcsFile->numTokens + 1); } else if ($commentStart === false || $tokens[$commentStart]['code'] !== T_DOC_COMMENT_OPEN_TAG ) { $phpcsFile->addError('Missing file doc comment', $errorToken, 'Missing'); $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'no'); return ($phpcsFile->numTokens + 1); } else { $phpcsFile->recordMetric($stackPtr, 'File has doc comment', 'yes'); } // Check each tag. $this->processTags($phpcsFile, $stackPtr, $commentStart); // Check there is 1 empty line after. $commentCloser = $tokens[$commentStart]['comment_closer']; $nextContentPtr = $phpcsFile->findNext(T_WHITESPACE, ($commentCloser + 1), null, true); $lineDiff = ($tokens[$nextContentPtr]['line'] - $tokens[$commentCloser]['line']); if ($lineDiff === 1) { $data = array(1); $error = 'Expected %s empty line after file doc comment'; $fix = $phpcsFile->addFixableError($error, ($commentCloser + 1), 'NoEmptyLineAfterFileDocComment', $data); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $phpcsFile->fixer->addNewlineBefore($nextContentPtr); $phpcsFile->fixer->endChangeset(); } } // Ignore the rest of the file. return ($phpcsFile->numTokens + 1); }
Processes this test, when one of its tokens is encountered. @param File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return int
entailment
protected function processPackage(File $phpcsFile, array $tags) { $tokens = $phpcsFile->getTokens(); foreach ($tags as $tag) { if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { // No content. continue; } $content = $tokens[($tag + 2)]['content']; $isInvalidPackage = false; if (strpos($content, '/') !== false) { $parts = explode('/', $content); $newName = join('\\', $parts); $isInvalidPackage = true; } if ($isInvalidPackage === true) { $error = 'Package name "%s" is not valid. Use "%s" instead'; $validName = trim($newName, '_'); $data = array( $content, $validName, ); $phpcsFile->addWarning($error, $tag, 'InvalidPackage', $data); } }//end foreach }
Process the package tag. @param File $phpcsFile The file being scanned. @param array $tags The tokens for these tags. @return void
entailment
protected function processCategory(File $phpcsFile, array $tags) { $tokens = $phpcsFile->getTokens(); foreach ($tags as $tag) { if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { // No content. continue; } $warning = 'The category tag is considered deprecated. It is recommended to use the @package tag instead.'; $phpcsFile->addWarning($warning, $tag, 'CategoryDepreciated'); }//end foreach }
Process the category tag. @param File $phpcsFile The file being scanned. @param array $tags The tokens for these tags. @return void
entailment
protected function processAuthor(File $phpcsFile, array $tags) { $tokens = $phpcsFile->getTokens(); foreach ($tags as $tag) { if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { // No content. continue; } $content = $tokens[($tag + 2)]['content']; // If it has an @ it's probably contains email address. if (strrpos($content, '@') !== false) { $local = '\da-zA-Z-_+'; // Dot character cannot be the first or last character in the local-part. $localMiddle = $local.'.\w'; if (preg_match('/^([^<]*)\s+<(['.$local.'](['.$localMiddle.']*['.$local.'])*@[\da-zA-Z][-.\w]*[\da-zA-Z]\.[a-zA-Z]{2,7})>$/', $content) === 0) { $error = '"@author" with email must be "Display Name <[email protected]>"'; $phpcsFile->addError($error, $tag, 'InvalidAuthors'); } } } }
Process the author tag(s) that this header comment has. @param File $phpcsFile The file being scanned. @param array $tags The tokens for these tags. @return void
entailment
protected function processCopyright(File $phpcsFile, array $tags) { $tokens = $phpcsFile->getTokens(); foreach ($tags as $tag) { if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { // No content. continue; } $content = $tokens[($tag + 2)]['content']; $matches = array(); if (preg_match('/^([0-9]{4})((.{1})([0-9]{4}))? (.+)$/', $content, $matches) !== 0) { // Check earliest-latest year order. if ($matches[3] !== '') { if ($matches[3] !== '-') { $error = 'A hyphen must be used between the earliest and latest year'; $phpcsFile->addError($error, $tag, 'CopyrightHyphen'); } if ($matches[4] !== '' && $matches[4] < $matches[1]) { $error = "Invalid year span \"$matches[1]$matches[3]$matches[4]\" found; consider \"$matches[4]-$matches[1]\" instead"; $phpcsFile->addWarning($error, $tag, 'InvalidCopyright'); } } } else { $error = '"@copyright" must be "YYYY [- YYYY] Name of the copyright holder"'; $phpcsFile->addError($error, $tag, 'IncompleteCopyright'); } }//end foreach }
Process the copyright tags. @param File $phpcsFile The file being scanned. @param array $tags The tokens for these tags. @return void
entailment
protected function processLicense(File $phpcsFile, array $tags) { $tokens = $phpcsFile->getTokens(); foreach ($tags as $tag) { if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { // No content. continue; } $content = $tokens[($tag + 2)]['content']; $matches = array(); preg_match('/^([^\s]+)\s+(.*)/', $content, $matches); if (count($matches) !== 3) { $error = '@license tag must contain a URL and a license name'; $phpcsFile->addError($error, $tag, 'IncompleteLicense'); } // Check the url is before the text part if it's included. $parts = explode(' ', $content); if ((count($parts) > 1)) { $matches = array(); preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $parts[0], $matches); if (count($matches) !== 1) { $error = 'The URL must come before the license name'; $phpcsFile->addError($error, $tag, 'LicenseURLNotFirst'); } } }//end foreach }
Process the license tag. @param File $phpcsFile The file being scanned. @param array $tags The tokens for these tags. @return void
entailment
protected function processVersion(File $phpcsFile, array $tags) { $tokens = $phpcsFile->getTokens(); foreach ($tags as $tag) { if ($tokens[($tag + 2)]['code'] !== T_DOC_COMMENT_STRING) { // No content. continue; } $content = $tokens[($tag + 2)]['content']; // Split into parts if content has a space. $parts = explode(' ', $content); // Check if the first part contains a semantic version number. $matches = array(); preg_match('/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/', $parts[0], $matches); if (strstr($content, 'CVS:') === false && strstr($content, 'SVN:') === false && strstr($content, 'GIT:') === false && strstr($content, 'HG:') === false && count($matches) === 0 ) { $error = 'It is recommended that @version is a semantic version number or is a VCS version vector "GIT: <git_id>" or "SVN: <svn_id>" or "HG: <hg_id>" or "CVS: <cvs_id>".'; $phpcsFile->addWarning($error, $tag, 'InvalidVersion'); } }//end foreach }
Process the version tag. @param File $phpcsFile The file being scanned. @param array $tags The tokens for these tags. @return void
entailment
public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $fileName = basename($phpcsFile->getFilename()); if (strpos($fileName, '_helper.php') !== false) { return; } $className = trim($phpcsFile->getDeclarationName($stackPtr)); if (strpos($className, 'Migration') === 0 && strpos($fileName, '_') !== false) { return; } $nextContentPtr = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); $type = $tokens[$stackPtr]['content']; if ($fileName !== $className.'.php' && $this->badFilename === false) { $data = array( $fileName, $className.'.php', ); $error = 'Filename "%s" doesn\'t match the expected filename "%s"'; $phpcsFile->addError($error, $nextContentPtr, ucfirst($type).'BadFilename', $data); $phpcsFile->recordMetric($nextContentPtr, 'Filename matches '.$type, 'no'); $this->badFilename = true; } else { $phpcsFile->recordMetric($nextContentPtr, 'Filename matches '.$type, 'yes'); } // Ignore the rest of the file. return ($phpcsFile->numTokens + 1); }
Processes this sniff, when one of its tokens is encountered. @param File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return int
entailment
protected function initializeExecute(OutputInterface $output, ProcessHelper $helper) { $this->execute = $this->execute ?: new Execute($output, $helper); }
Initialize the execute property if necessary. @param OutputInterface $output @param ProcessHelper $helper
entailment
public function getRate($fromCurrency, $toCurrency) { $path = sprintf( '%s' . self::FIXER_API_BASEPATH . '?access_key=%s&symbols=%s&base=%s', ($this->useHttps) ? 'https://' : 'http://', $this->accessKey, $toCurrency, $fromCurrency ); $result = json_decode($this->httpClient->get($path)->getBody(), true); if (!isset($result['rates'][$toCurrency])) { throw new UnsupportedCurrencyException(sprintf('Undefined rate for "%s" currency.', $toCurrency)); } return $result['rates'][$toCurrency]; }
{@inheritdoc}
entailment
public function resolveRequirements(Plugin $plugin, $moodleVersion) { $map = [ 'auth' => new AuthRequirements($plugin, $moodleVersion), 'block' => new BlockRequirements($plugin, $moodleVersion), 'filter' => new FilterRequirements($plugin, $moodleVersion), 'format' => new FormatRequirements($plugin, $moodleVersion), 'mod' => new ModuleRequirements($plugin, $moodleVersion), 'qtype' => new QuestionRequirements($plugin, $moodleVersion), 'repository' => new RepositoryRequirements($plugin, $moodleVersion), 'theme' => new ThemeRequirements($plugin, $moodleVersion), ]; if (array_key_exists($plugin->type, $map)) { return $map[$plugin->type]; } return new GenericRequirements($plugin, $moodleVersion); }
Find the requirements for a given plugin type. @param Plugin $plugin @param int $moodleVersion @return AbstractRequirements
entailment
protected function loadFile($path) { if (pathinfo($path, PATHINFO_EXTENSION) !== 'php') { throw new \InvalidArgumentException('Can only parse files with ".php" extensions'); } if (!file_exists($path)) { throw new \InvalidArgumentException(sprintf('Failed to find \'%s\' file.', $path)); } return file_get_contents($path); }
Loads the contents of a file. @param string $path File path @return string
entailment
public function parseFile($path) { $factory = new ParserFactory(); $parser = $factory->create(ParserFactory::PREFER_PHP7); try { $statements = $parser->parse($this->loadFile($path)); } catch (Error $e) { throw new \RuntimeException(sprintf('Failed to parse %s file due to parse error: %s', $path, $e->getMessage()), 0, $e); } if ($statements === null) { throw new \RuntimeException(sprintf('Failed to parse %s', $path)); } return $statements; }
Parse a PHP file. @param string $path File path @throws \Exception @return \PhpParser\Node[]
entailment
private function resolveOptions(InputInterface $input) { $options = []; if ($this->supportsCoverage() && $input->getOption('coverage-text')) { $options[] = '--coverage-text'; } if ($this->supportsCoverage() && $input->getOption('coverage-clover')) { $options[] = sprintf('--coverage-clover %s/coverage.xml', getcwd()); } if (is_file($this->plugin->directory.'/phpunit.xml')) { $options[] = sprintf('--configuration %s', $this->plugin->directory); } else { $options[] = sprintf('--testsuite %s_testsuite', $this->plugin->getComponent()); } return implode(' ', $options); }
Resolve options for PHPUnit command. @param InputInterface $input @return string
entailment
protected function findTables($file) { $tables = []; $xml = simplexml_load_file($file); foreach ($xml->xpath('TABLES/TABLE') as $element) { if (null !== $element['NAME']) { $tables[] = (string) $element['NAME']; } } return $tables; }
@param string $file @return array
entailment
public function run($cmd, $error = null) { return $this->helper->run($this->output, $cmd, $error); }
@param string|array|Process $cmd An instance of Process or an array of arguments to escape and run or a command to run @param string|null $error An error message that must be displayed if something went wrong @return Process
entailment
public function mustRun($cmd, $error = null) { return $this->helper->mustRun($this->output, $cmd, $error); }
@param string|array|Process $cmd An instance of Process or an array of arguments to escape and run or a command to run @param string|null $error An error message that must be displayed if something went wrong @return Process
entailment
public function passThrough($commandline, $cwd = null, $timeout = null) { return $this->passThroughProcess(new Process($commandline, $cwd, null, null, $timeout)); }
Run a command and send output, unaltered, immediately. @param string $commandline The command line to run @param string|null $cwd The working directory or null to use the working dir of the current PHP process @param int|float|null $timeout The timeout in seconds or null to disable @return Process
entailment
public function passThroughProcess(Process $process) { if ($this->output->isVeryVerbose()) { $this->output->writeln(sprintf('<bg=blue;fg=white;> RUN </> <fg=blue>%s</>', $process->getCommandLine())); } $process->run(function ($type, $buffer) { $this->output->write($buffer); }); return $process; }
Run a process and send output, unaltered, immediately. @param Process $process @return Process
entailment
public function getRate($fromCurrency, $toCurrency) { $path = sprintf( self::EXCHANGERATESIO_API_BASEPATH . '?symbols=%s&base=%s', $toCurrency, $fromCurrency ); $result = json_decode($this->httpClient->get($path)->getBody(), true); if (!isset($result['rates'][$toCurrency])) { throw new UnsupportedCurrencyException(sprintf('Undefined rate for "%s" currency.', $toCurrency)); } return $result['rates'][$toCurrency]; }
{@inheritdoc}
entailment
public function requireConfig() { global $CFG; if (!defined('CLI_SCRIPT')) { define('CLI_SCRIPT', true); } if (!defined('IGNORE_COMPONENT_CACHE')) { define('IGNORE_COMPONENT_CACHE', true); } if (!defined('CACHE_DISABLE_ALL')) { define('CACHE_DISABLE_ALL', true); } if (!defined('ABORT_AFTER_CONFIG')) { // Need this since Moodle will not be fully installed. define('ABORT_AFTER_CONFIG', true); } $path = $this->directory.'/config.php'; if (!is_file($path)) { throw new \RuntimeException('Failed to find Moodle config file'); } /** @noinspection PhpIncludeInspection */ require_once $path; // Save a local reference to Moodle's config. if (empty($this->cfg)) { $this->cfg = $CFG; } }
Load's Moodle config so we can use Moodle APIs.
entailment
public function getComponentInstallDirectory($component) { list($type, $name) = $this->normalizeComponent($component); // Must use reflection to avoid using static cache. $method = new \ReflectionMethod('core_component', 'fetch_plugintypes'); $method->setAccessible(true); $result = $method->invoke(null); if (!array_key_exists($type, $result[0])) { throw new \InvalidArgumentException(sprintf('The component %s has an unknown plugin type of %s', $component, $type)); } return $result[0][$type].'/'.$name; }
Get the absolute install directory path within Moodle. @param string $component Moodle component, EG: mod_forum @return string Absolute path, EG: /path/to/mod/forum
entailment
public function getBranch() { $filter = new StatementFilter(); $parser = new CodeParser(); $statements = $parser->parseFile($this->directory.'/version.php'); $assign = $filter->findFirstVariableAssignment($statements, 'branch', 'Failed to find $branch in Moodle version.php'); if ($assign->expr instanceof String_) { return (int) $assign->expr->value; } throw new \RuntimeException('Failed to find Moodle branch version'); }
Get the branch number, EG: 29, 30, etc. @return int
entailment
public function getConfig($name) { $this->requireConfig(); if (!property_exists($this->cfg, $name)) { throw new \RuntimeException(sprintf('Failed to find $CFG->%s in Moodle config file', $name)); } return $this->cfg->$name; }
Get a Moodle config value. @param string $name the config name @return string
entailment
public function resolveDatabase($type, $name = null, $user = null, $pass = null, $host = null) { $database = $this->resolveDatabaseType($type); if ($name !== null) { $database->name = $name; } if ($user !== null) { $database->user = $user; } if ($pass !== null) { $database->pass = $pass; } if ($host !== null) { $database->host = $host; } return $database; }
@param string $type @param string|null $name @param string|null $user @param string|null $pass @param string|null $host @return AbstractDatabase
entailment
private function resolveDatabaseType($type) { foreach ($this->getDatabases() as $database) { if ($database->type === $type) { return $database; } } throw new \DomainException(sprintf('Unknown database type (%s). Please use mysqli, pgsql or mariadb.', $type)); }
Resolve database class. @param string $type Database type @return AbstractDatabase
entailment
public function createContents(AbstractDatabase $database, $dataDir) { $template = file_get_contents(__DIR__.'/../../res/template/config.php.txt'); $variables = [ '{{DBTYPE}}' => $database->type, '{{DBLIBRARY}}' => $database->library, '{{DBHOST}}' => $database->host, '{{DBNAME}}' => $database->name, '{{DBUSER}}' => $database->user, '{{DBPASS}}' => $database->pass, '{{WWWROOT}}' => 'http://localhost/moodle', '{{DATAROOT}}' => $dataDir, '{{PHPUNITDATAROOT}}' => $dataDir.'/phpu_moodledata', '{{BEHATDATAROOT}}' => $dataDir.'/behat_moodledata', '{{BEHATDUMP}}' => $dataDir.'/behat_dump', '{{BEHATWWWROOT}}' => 'http://localhost:8000', '{{EXTRACONFIG}}' => self::PLACEHOLDER, ]; return str_replace(array_keys($variables), array_values($variables), $template); }
Create a Moodle config. @param AbstractDatabase $database @param string $dataDir Absolute path to data directory @return string
entailment
public function injectLine($contents, $lineToAdd) { if (strpos($contents, self::PLACEHOLDER) === false) { throw new \RuntimeException('Failed to find placeholder in config file, file might be malformed'); } return str_replace(self::PLACEHOLDER, $lineToAdd."\n".self::PLACEHOLDER, $contents); }
Adds a line of PHP code into the config file. @param string $contents The config file contents @param string $lineToAdd The line to inject @return string
entailment
public function read($file) { if (!file_exists($file)) { throw new \InvalidArgumentException('Failed to find Moodle config.php file, perhaps Moodle has not been installed yet'); } // Must suppress as unreadable files emit PHP warning, but we handle it below. $contents = @file_get_contents($file); if ($contents === false) { throw new \RuntimeException('Failed to read from the Moodle config.php file'); } return $contents; }
Read a config file. @param string $file Path to the file to read @return string
entailment