refactor: convert some block generators to goog.module (#5770)

* refactor: convert generators/lua.js to goog.module

* refactor: convert generator/lua.js to named requires

* chore: run clang-format

* refactor: convert generators/php/colour.js to goog.module

* refactor: convert generators/php/colour.js to named requires

* chore: run clang-format

* refactor: convert generators/php/lists.js to goog.module

* refactor: convert generators/php/lists.js to named requires

* chore: run clang-format

* refactor: convert generators/php/logic.js to goog.module

* refactor: convert generators/php/logic.js to named requires

* chore: run clang-format

* refactor: convert generators/php/loops.js to goog.module

* refactor: convert generators/php/loops.js to named requires

* chore: run clang-format

* refactor: convert generators/php/math.js to goog.module

* refactor: convert generators/php/math.js to named requires

* chore: run clang-format

* refactor: convert generators/php/procedures.js to goog.module

* refactor: convert generators/php/procedures.js to named requires

* chore: run clang-format

* refactor: convert generators/php/text.js to goog.module

* refactor: convert generators/php/text.js to named requires

* chore: run clang-format

* refactor: convert generators/php/variables.js to goog.module

* refactor: convert generators/php/variables.js to named requires

* chore: run clang-format

* refactor: convert generators/php/variables_dynamic.js to goog.module

* refactor: convert generators/php/variables_dynamic.js to named requires

* refactor: convert generators/php.js to goog.module

* refactor: convert generators/php.js to named requires

* chore: run clang-format

* chore: rebuild deps.js
This commit is contained in:
Rachel Fenichel
2021-12-01 17:59:20 -08:00
committed by GitHub
parent a939fec53b
commit c0517ea360
12 changed files with 809 additions and 961 deletions

View File

@@ -11,22 +11,23 @@
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua'); goog.module('Blockly.Lua');
goog.module.declareLegacyNamespace();
goog.require('Blockly.Generator'); const objectUtils = goog.require('Blockly.utils.object');
goog.require('Blockly.Names'); const stringUtils = goog.require('Blockly.utils.string');
goog.require('Blockly.inputTypes'); const {Block} = goog.requireType('Blockly.Block');
goog.require('Blockly.utils.object'); const {Generator} = goog.require('Blockly.Generator');
goog.require('Blockly.utils.string'); const {inputTypes} = goog.require('Blockly.inputTypes');
goog.requireType('Blockly.Block'); const {Names} = goog.require('Blockly.Names');
goog.requireType('Blockly.Workspace'); const {Workspace} = goog.requireType('Blockly.Workspace');
/** /**
* Lua code generator. * Lua code generator.
* @type {!Blockly.Generator} * @type {!Generator}
*/ */
Blockly.Lua = new Blockly.Generator('Lua'); const Lua = new Generator('Lua');
/** /**
* List of illegal variable names. * List of illegal variable names.
@@ -35,7 +36,7 @@ Blockly.Lua = new Blockly.Generator('Lua');
* accidentally clobbering a built-in object or function. * accidentally clobbering a built-in object or function.
* @private * @private
*/ */
Blockly.Lua.addReservedWords( Lua.addReservedWords(
// Special character // Special character
'_,' + '_,' +
// From theoriginalbit's script: // From theoriginalbit's script:
@@ -58,25 +59,24 @@ Blockly.Lua.addReservedWords(
'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' + 'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' +
'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' + 'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' +
// Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3). // Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3).
'require,package,string,table,math,bit32,io,file,os,debug' 'require,package,string,table,math,bit32,io,file,os,debug');
);
/** /**
* Order of operation ENUMs. * Order of operation ENUMs.
* http://www.lua.org/manual/5.3/manual.html#3.4.8 * http://www.lua.org/manual/5.3/manual.html#3.4.8
*/ */
Blockly.Lua.ORDER_ATOMIC = 0; // literals Lua.ORDER_ATOMIC = 0; // literals
// The next level was not explicit in documentation and inferred by Ellen. // The next level was not explicit in documentation and inferred by Ellen.
Blockly.Lua.ORDER_HIGH = 1; // Function calls, tables[] Lua.ORDER_HIGH = 1; // Function calls, tables[]
Blockly.Lua.ORDER_EXPONENTIATION = 2; // ^ Lua.ORDER_EXPONENTIATION = 2; // ^
Blockly.Lua.ORDER_UNARY = 3; // not # - ~ Lua.ORDER_UNARY = 3; // not # - ~
Blockly.Lua.ORDER_MULTIPLICATIVE = 4; // * / % Lua.ORDER_MULTIPLICATIVE = 4; // * / %
Blockly.Lua.ORDER_ADDITIVE = 5; // + - Lua.ORDER_ADDITIVE = 5; // + -
Blockly.Lua.ORDER_CONCATENATION = 6; // .. Lua.ORDER_CONCATENATION = 6; // ..
Blockly.Lua.ORDER_RELATIONAL = 7; // < > <= >= ~= == Lua.ORDER_RELATIONAL = 7; // < > <= >= ~= ==
Blockly.Lua.ORDER_AND = 8; // and Lua.ORDER_AND = 8; // and
Blockly.Lua.ORDER_OR = 9; // or Lua.ORDER_OR = 9; // or
Blockly.Lua.ORDER_NONE = 99; Lua.ORDER_NONE = 99;
/** /**
* Note: Lua is not supporting zero-indexing since the language itself is * Note: Lua is not supporting zero-indexing since the language itself is
@@ -88,18 +88,18 @@ Blockly.Lua.ORDER_NONE = 99;
* Whether the init method has been called. * Whether the init method has been called.
* @type {?boolean} * @type {?boolean}
*/ */
Blockly.Lua.isInitialized = false; Lua.isInitialized = false;
/** /**
* Initialise the database of variable names. * Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from. * @param {!Workspace} workspace Workspace to generate code from.
*/ */
Blockly.Lua.init = function(workspace) { Lua.init = function(workspace) {
// Call Blockly.Generator's init. // Call Blockly.Generator's init.
Object.getPrototypeOf(this).init.call(this); Object.getPrototypeOf(this).init.call(this);
if (!this.nameDB_) { if (!this.nameDB_) {
this.nameDB_ = new Blockly.Names(this.RESERVED_WORDS_); this.nameDB_ = new Names(this.RESERVED_WORDS_);
} else { } else {
this.nameDB_.reset(); this.nameDB_.reset();
} }
@@ -115,9 +115,9 @@ Blockly.Lua.init = function(workspace) {
* @param {string} code Generated code. * @param {string} code Generated code.
* @return {string} Completed code. * @return {string} Completed code.
*/ */
Blockly.Lua.finish = function(code) { Lua.finish = function(code) {
// Convert the definitions dictionary into a list. // Convert the definitions dictionary into a list.
const definitions = Blockly.utils.object.values(this.definitions_); const definitions = objectUtils.values(this.definitions_);
// Call Blockly.Generator's finish. // Call Blockly.Generator's finish.
code = Object.getPrototypeOf(this).finish.call(this, code); code = Object.getPrototypeOf(this).finish.call(this, code);
this.isInitialized = false; this.isInitialized = false;
@@ -134,7 +134,7 @@ Blockly.Lua.finish = function(code) {
* @param {string} line Line of generated code. * @param {string} line Line of generated code.
* @return {string} Legal line of code. * @return {string} Legal line of code.
*/ */
Blockly.Lua.scrubNakedValue = function(line) { Lua.scrubNakedValue = function(line) {
return 'local _ = ' + line + '\n'; return 'local _ = ' + line + '\n';
}; };
@@ -145,10 +145,10 @@ Blockly.Lua.scrubNakedValue = function(line) {
* @return {string} Lua string. * @return {string} Lua string.
* @protected * @protected
*/ */
Blockly.Lua.quote_ = function(string) { Lua.quote_ = function(string) {
string = string.replace(/\\/g, '\\\\') string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n') .replace(/\n/g, '\\\n')
.replace(/'/g, '\\\''); .replace(/'/g, '\\\'');
return '\'' + string + '\''; return '\'' + string + '\'';
}; };
@@ -159,7 +159,7 @@ Blockly.Lua.quote_ = function(string) {
* @return {string} Lua string. * @return {string} Lua string.
* @protected * @protected
*/ */
Blockly.Lua.multiline_quote_ = function(string) { Lua.multiline_quote_ = function(string) {
const lines = string.split(/\n/g).map(this.quote_); const lines = string.split(/\n/g).map(this.quote_);
// Join with the following, plus a newline: // Join with the following, plus a newline:
// .. '\n' .. // .. '\n' ..
@@ -170,26 +170,26 @@ Blockly.Lua.multiline_quote_ = function(string) {
* Common tasks for generating Lua from blocks. * Common tasks for generating Lua from blocks.
* Handles comments for the specified block and any connected value blocks. * Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block. * Calls any statements following this block.
* @param {!Blockly.Block} block The current block. * @param {!Block} block The current block.
* @param {string} code The Lua code created for this block. * @param {string} code The Lua code created for this block.
* @param {boolean=} opt_thisOnly True to generate code for only this statement. * @param {boolean=} opt_thisOnly True to generate code for only this statement.
* @return {string} Lua code with comments and subsequent blocks added. * @return {string} Lua code with comments and subsequent blocks added.
* @protected * @protected
*/ */
Blockly.Lua.scrub_ = function(block, code, opt_thisOnly) { Lua.scrub_ = function(block, code, opt_thisOnly) {
let commentCode = ''; let commentCode = '';
// Only collect comments for blocks that aren't inline. // Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) { if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block. // Collect comment for this block.
let comment = block.getCommentText(); let comment = block.getCommentText();
if (comment) { if (comment) {
comment = Blockly.utils.string.wrap(comment, this.COMMENT_WRAP - 3); comment = stringUtils.wrap(comment, this.COMMENT_WRAP - 3);
commentCode += this.prefixLines(comment, '-- ') + '\n'; commentCode += this.prefixLines(comment, '-- ') + '\n';
} }
// Collect comments for all value arguments. // Collect comments for all value arguments.
// Don't collect comments for nested statements. // Don't collect comments for nested statements.
for (let i = 0; i < block.inputList.length; i++) { for (let i = 0; i < block.inputList.length; i++) {
if (block.inputList[i].type === Blockly.inputTypes.VALUE) { if (block.inputList[i].type === inputTypes.VALUE) {
const childBlock = block.inputList[i].connection.targetBlock(); const childBlock = block.inputList[i].connection.targetBlock();
if (childBlock) { if (childBlock) {
comment = this.allNestedComments(childBlock); comment = this.allNestedComments(childBlock);
@@ -204,3 +204,5 @@ Blockly.Lua.scrub_ = function(block, code, opt_thisOnly) {
const nextCode = opt_thisOnly ? '' : this.blockToCode(nextBlock); const nextCode = opt_thisOnly ? '' : this.blockToCode(nextBlock);
return commentCode + code + nextCode; return commentCode + code + nextCode;
}; };
exports = Lua;

View File

@@ -10,22 +10,23 @@
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP'); goog.module('Blockly.PHP');
goog.module.declareLegacyNamespace();
goog.require('Blockly.Generator'); const objectUtils = goog.require('Blockly.utils.object');
goog.require('Blockly.Names'); const stringUtils = goog.require('Blockly.utils.string');
goog.require('Blockly.inputTypes'); const {Block} = goog.requireType('Blockly.Block');
goog.require('Blockly.utils.object'); const {Generator} = goog.require('Blockly.Generator');
goog.require('Blockly.utils.string'); const {inputTypes} = goog.require('Blockly.inputTypes');
goog.requireType('Blockly.Block'); const {Names} = goog.require('Blockly.Names');
goog.requireType('Blockly.Workspace'); const {Workspace} = goog.requireType('Blockly.Workspace');
/** /**
* PHP code generator. * PHP code generator.
* @type {!Blockly.Generator} * @type {!Generator}
*/ */
Blockly.PHP = new Blockly.Generator('PHP'); const PHP = new Generator('PHP');
/** /**
* List of illegal variable names. * List of illegal variable names.
@@ -34,8 +35,8 @@ Blockly.PHP = new Blockly.Generator('PHP');
* accidentally clobbering a built-in object or function. * accidentally clobbering a built-in object or function.
* @private * @private
*/ */
Blockly.PHP.addReservedWords( PHP.addReservedWords(
// http://php.net/manual/en/reserved.keywords.php // http://php.net/manual/en/reserved.keywords.php
'__halt_compiler,abstract,and,array,as,break,callable,case,catch,class,' + '__halt_compiler,abstract,and,array,as,break,callable,case,catch,class,' +
'clone,const,continue,declare,default,die,do,echo,else,elseif,empty,' + 'clone,const,continue,declare,default,die,do,echo,else,elseif,empty,' +
'enddeclare,endfor,endforeach,endif,endswitch,endwhile,eval,exit,extends,' + 'enddeclare,endfor,endforeach,endif,endswitch,endwhile,eval,exit,extends,' +
@@ -43,7 +44,7 @@ Blockly.PHP.addReservedWords(
'include_once,instanceof,insteadof,interface,isset,list,namespace,new,or,' + 'include_once,instanceof,insteadof,interface,isset,list,namespace,new,or,' +
'print,private,protected,public,require,require_once,return,static,' + 'print,private,protected,public,require,require_once,return,static,' +
'switch,throw,trait,try,unset,use,var,while,xor,' + 'switch,throw,trait,try,unset,use,var,while,xor,' +
// http://php.net/manual/en/reserved.constants.php // http://php.net/manual/en/reserved.constants.php
'PHP_VERSION,PHP_MAJOR_VERSION,PHP_MINOR_VERSION,PHP_RELEASE_VERSION,' + 'PHP_VERSION,PHP_MAJOR_VERSION,PHP_MINOR_VERSION,PHP_RELEASE_VERSION,' +
'PHP_VERSION_ID,PHP_EXTRA_VERSION,PHP_ZTS,PHP_DEBUG,PHP_MAXPATHLEN,' + 'PHP_VERSION_ID,PHP_EXTRA_VERSION,PHP_ZTS,PHP_DEBUG,PHP_MAXPATHLEN,' +
'PHP_OS,PHP_SAPI,PHP_EOL,PHP_INT_MAX,PHP_INT_SIZE,DEFAULT_INCLUDE_PATH,' + 'PHP_OS,PHP_SAPI,PHP_EOL,PHP_INT_MAX,PHP_INT_SIZE,DEFAULT_INCLUDE_PATH,' +
@@ -54,90 +55,89 @@ Blockly.PHP.addReservedWords(
'E_CORE_WARNING,E_COMPILE_ERROR,E_COMPILE_WARNING,E_USER_ERROR,' + 'E_CORE_WARNING,E_COMPILE_ERROR,E_COMPILE_WARNING,E_USER_ERROR,' +
'E_USER_WARNING,E_USER_NOTICE,E_DEPRECATED,E_USER_DEPRECATED,E_ALL,' + 'E_USER_WARNING,E_USER_NOTICE,E_DEPRECATED,E_USER_DEPRECATED,E_ALL,' +
'E_STRICT,__COMPILER_HALT_OFFSET__,TRUE,FALSE,NULL,__CLASS__,__DIR__,' + 'E_STRICT,__COMPILER_HALT_OFFSET__,TRUE,FALSE,NULL,__CLASS__,__DIR__,' +
'__FILE__,__FUNCTION__,__LINE__,__METHOD__,__NAMESPACE__,__TRAIT__' '__FILE__,__FUNCTION__,__LINE__,__METHOD__,__NAMESPACE__,__TRAIT__');
);
/** /**
* Order of operation ENUMs. * Order of operation ENUMs.
* http://php.net/manual/en/language.operators.precedence.php * http://php.net/manual/en/language.operators.precedence.php
*/ */
Blockly.PHP.ORDER_ATOMIC = 0; // 0 "" ... PHP.ORDER_ATOMIC = 0; // 0 "" ...
Blockly.PHP.ORDER_CLONE = 1; // clone PHP.ORDER_CLONE = 1; // clone
Blockly.PHP.ORDER_NEW = 1; // new PHP.ORDER_NEW = 1; // new
Blockly.PHP.ORDER_MEMBER = 2.1; // [] PHP.ORDER_MEMBER = 2.1; // []
Blockly.PHP.ORDER_FUNCTION_CALL = 2.2; // () PHP.ORDER_FUNCTION_CALL = 2.2; // ()
Blockly.PHP.ORDER_POWER = 3; // ** PHP.ORDER_POWER = 3; // **
Blockly.PHP.ORDER_INCREMENT = 4; // ++ PHP.ORDER_INCREMENT = 4; // ++
Blockly.PHP.ORDER_DECREMENT = 4; // -- PHP.ORDER_DECREMENT = 4; // --
Blockly.PHP.ORDER_BITWISE_NOT = 4; // ~ PHP.ORDER_BITWISE_NOT = 4; // ~
Blockly.PHP.ORDER_CAST = 4; // (int) (float) (string) (array) ... PHP.ORDER_CAST = 4; // (int) (float) (string) (array) ...
Blockly.PHP.ORDER_SUPPRESS_ERROR = 4; // @ PHP.ORDER_SUPPRESS_ERROR = 4; // @
Blockly.PHP.ORDER_INSTANCEOF = 5; // instanceof PHP.ORDER_INSTANCEOF = 5; // instanceof
Blockly.PHP.ORDER_LOGICAL_NOT = 6; // ! PHP.ORDER_LOGICAL_NOT = 6; // !
Blockly.PHP.ORDER_UNARY_PLUS = 7.1; // + PHP.ORDER_UNARY_PLUS = 7.1; // +
Blockly.PHP.ORDER_UNARY_NEGATION = 7.2; // - PHP.ORDER_UNARY_NEGATION = 7.2; // -
Blockly.PHP.ORDER_MULTIPLICATION = 8.1; // * PHP.ORDER_MULTIPLICATION = 8.1; // *
Blockly.PHP.ORDER_DIVISION = 8.2; // / PHP.ORDER_DIVISION = 8.2; // /
Blockly.PHP.ORDER_MODULUS = 8.3; // % PHP.ORDER_MODULUS = 8.3; // %
Blockly.PHP.ORDER_ADDITION = 9.1; // + PHP.ORDER_ADDITION = 9.1; // +
Blockly.PHP.ORDER_SUBTRACTION = 9.2; // - PHP.ORDER_SUBTRACTION = 9.2; // -
Blockly.PHP.ORDER_STRING_CONCAT = 9.3; // . PHP.ORDER_STRING_CONCAT = 9.3; // .
Blockly.PHP.ORDER_BITWISE_SHIFT = 10; // << >> PHP.ORDER_BITWISE_SHIFT = 10; // << >>
Blockly.PHP.ORDER_RELATIONAL = 11; // < <= > >= PHP.ORDER_RELATIONAL = 11; // < <= > >=
Blockly.PHP.ORDER_EQUALITY = 12; // == != === !== <> <=> PHP.ORDER_EQUALITY = 12; // == != === !== <> <=>
Blockly.PHP.ORDER_REFERENCE = 13; // & PHP.ORDER_REFERENCE = 13; // &
Blockly.PHP.ORDER_BITWISE_AND = 13; // & PHP.ORDER_BITWISE_AND = 13; // &
Blockly.PHP.ORDER_BITWISE_XOR = 14; // ^ PHP.ORDER_BITWISE_XOR = 14; // ^
Blockly.PHP.ORDER_BITWISE_OR = 15; // | PHP.ORDER_BITWISE_OR = 15; // |
Blockly.PHP.ORDER_LOGICAL_AND = 16; // && PHP.ORDER_LOGICAL_AND = 16; // &&
Blockly.PHP.ORDER_LOGICAL_OR = 17; // || PHP.ORDER_LOGICAL_OR = 17; // ||
Blockly.PHP.ORDER_IF_NULL = 18; // ?? PHP.ORDER_IF_NULL = 18; // ??
Blockly.PHP.ORDER_CONDITIONAL = 19; // ?: PHP.ORDER_CONDITIONAL = 19; // ?:
Blockly.PHP.ORDER_ASSIGNMENT = 20; // = += -= *= /= %= <<= >>= ... PHP.ORDER_ASSIGNMENT = 20; // = += -= *= /= %= <<= >>= ...
Blockly.PHP.ORDER_LOGICAL_AND_WEAK = 21; // and PHP.ORDER_LOGICAL_AND_WEAK = 21; // and
Blockly.PHP.ORDER_LOGICAL_XOR = 22; // xor PHP.ORDER_LOGICAL_XOR = 22; // xor
Blockly.PHP.ORDER_LOGICAL_OR_WEAK = 23; // or PHP.ORDER_LOGICAL_OR_WEAK = 23; // or
Blockly.PHP.ORDER_NONE = 99; // (...) PHP.ORDER_NONE = 99; // (...)
/** /**
* List of outer-inner pairings that do NOT require parentheses. * List of outer-inner pairings that do NOT require parentheses.
* @type {!Array<!Array<number>>} * @type {!Array<!Array<number>>}
*/ */
Blockly.PHP.ORDER_OVERRIDES = [ PHP.ORDER_OVERRIDES = [
// (foo()).bar() -> foo().bar() // (foo()).bar() -> foo().bar()
// (foo())[0] -> foo()[0] // (foo())[0] -> foo()[0]
[Blockly.PHP.ORDER_MEMBER, Blockly.PHP.ORDER_FUNCTION_CALL], [PHP.ORDER_MEMBER, PHP.ORDER_FUNCTION_CALL],
// (foo[0])[1] -> foo[0][1] // (foo[0])[1] -> foo[0][1]
// (foo.bar).baz -> foo.bar.baz // (foo.bar).baz -> foo.bar.baz
[Blockly.PHP.ORDER_MEMBER, Blockly.PHP.ORDER_MEMBER], [PHP.ORDER_MEMBER, PHP.ORDER_MEMBER],
// !(!foo) -> !!foo // !(!foo) -> !!foo
[Blockly.PHP.ORDER_LOGICAL_NOT, Blockly.PHP.ORDER_LOGICAL_NOT], [PHP.ORDER_LOGICAL_NOT, PHP.ORDER_LOGICAL_NOT],
// a * (b * c) -> a * b * c // a * (b * c) -> a * b * c
[Blockly.PHP.ORDER_MULTIPLICATION, Blockly.PHP.ORDER_MULTIPLICATION], [PHP.ORDER_MULTIPLICATION, PHP.ORDER_MULTIPLICATION],
// a + (b + c) -> a + b + c // a + (b + c) -> a + b + c
[Blockly.PHP.ORDER_ADDITION, Blockly.PHP.ORDER_ADDITION], [PHP.ORDER_ADDITION, PHP.ORDER_ADDITION],
// a && (b && c) -> a && b && c // a && (b && c) -> a && b && c
[Blockly.PHP.ORDER_LOGICAL_AND, Blockly.PHP.ORDER_LOGICAL_AND], [PHP.ORDER_LOGICAL_AND, PHP.ORDER_LOGICAL_AND],
// a || (b || c) -> a || b || c // a || (b || c) -> a || b || c
[Blockly.PHP.ORDER_LOGICAL_OR, Blockly.PHP.ORDER_LOGICAL_OR] [PHP.ORDER_LOGICAL_OR, PHP.ORDER_LOGICAL_OR]
]; ];
/** /**
* Whether the init method has been called. * Whether the init method has been called.
* @type {?boolean} * @type {?boolean}
*/ */
Blockly.PHP.isInitialized = false; PHP.isInitialized = false;
/** /**
* Initialise the database of variable names. * Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from. * @param {!Workspace} workspace Workspace to generate code from.
*/ */
Blockly.PHP.init = function(workspace) { PHP.init = function(workspace) {
// Call Blockly.Generator's init. // Call Blockly.Generator's init.
Object.getPrototypeOf(this).init.call(this); Object.getPrototypeOf(this).init.call(this);
if (!this.nameDB_) { if (!this.nameDB_) {
this.nameDB_ = new Blockly.Names(this.RESERVED_WORDS_, '$'); this.nameDB_ = new Names(this.RESERVED_WORDS_, '$');
} else { } else {
this.nameDB_.reset(); this.nameDB_.reset();
} }
@@ -154,9 +154,9 @@ Blockly.PHP.init = function(workspace) {
* @param {string} code Generated code. * @param {string} code Generated code.
* @return {string} Completed code. * @return {string} Completed code.
*/ */
Blockly.PHP.finish = function(code) { PHP.finish = function(code) {
// Convert the definitions dictionary into a list. // Convert the definitions dictionary into a list.
const definitions = Blockly.utils.object.values(this.definitions_); const definitions = objectUtils.values(this.definitions_);
// Call Blockly.Generator's finish. // Call Blockly.Generator's finish.
code = Object.getPrototypeOf(this).finish.call(this, code); code = Object.getPrototypeOf(this).finish.call(this, code);
this.isInitialized = false; this.isInitialized = false;
@@ -171,7 +171,7 @@ Blockly.PHP.finish = function(code) {
* @param {string} line Line of generated code. * @param {string} line Line of generated code.
* @return {string} Legal line of code. * @return {string} Legal line of code.
*/ */
Blockly.PHP.scrubNakedValue = function(line) { PHP.scrubNakedValue = function(line) {
return line + ';\n'; return line + ';\n';
}; };
@@ -182,10 +182,10 @@ Blockly.PHP.scrubNakedValue = function(line) {
* @return {string} PHP string. * @return {string} PHP string.
* @protected * @protected
*/ */
Blockly.PHP.quote_ = function(string) { PHP.quote_ = function(string) {
string = string.replace(/\\/g, '\\\\') string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n') .replace(/\n/g, '\\\n')
.replace(/'/g, '\\\''); .replace(/'/g, '\\\'');
return '\'' + string + '\''; return '\'' + string + '\'';
}; };
@@ -196,7 +196,7 @@ Blockly.PHP.quote_ = function(string) {
* @return {string} PHP string. * @return {string} PHP string.
* @protected * @protected
*/ */
Blockly.PHP.multiline_quote_ = function (string) { PHP.multiline_quote_ = function(string) {
const lines = string.split(/\n/g).map(this.quote_); const lines = string.split(/\n/g).map(this.quote_);
// Join with the following, plus a newline: // Join with the following, plus a newline:
// . "\n" . // . "\n" .
@@ -208,26 +208,26 @@ Blockly.PHP.multiline_quote_ = function (string) {
* Common tasks for generating PHP from blocks. * Common tasks for generating PHP from blocks.
* Handles comments for the specified block and any connected value blocks. * Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block. * Calls any statements following this block.
* @param {!Blockly.Block} block The current block. * @param {!Block} block The current block.
* @param {string} code The PHP code created for this block. * @param {string} code The PHP code created for this block.
* @param {boolean=} opt_thisOnly True to generate code for only this statement. * @param {boolean=} opt_thisOnly True to generate code for only this statement.
* @return {string} PHP code with comments and subsequent blocks added. * @return {string} PHP code with comments and subsequent blocks added.
* @protected * @protected
*/ */
Blockly.PHP.scrub_ = function(block, code, opt_thisOnly) { PHP.scrub_ = function(block, code, opt_thisOnly) {
let commentCode = ''; let commentCode = '';
// Only collect comments for blocks that aren't inline. // Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) { if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block. // Collect comment for this block.
let comment = block.getCommentText(); let comment = block.getCommentText();
if (comment) { if (comment) {
comment = Blockly.utils.string.wrap(comment, this.COMMENT_WRAP - 3); comment = stringUtils.wrap(comment, this.COMMENT_WRAP - 3);
commentCode += this.prefixLines(comment, '// ') + '\n'; commentCode += this.prefixLines(comment, '// ') + '\n';
} }
// Collect comments for all value arguments. // Collect comments for all value arguments.
// Don't collect comments for nested statements. // Don't collect comments for nested statements.
for (let i = 0; i < block.inputList.length; i++) { for (let i = 0; i < block.inputList.length; i++) {
if (block.inputList[i].type === Blockly.inputTypes.VALUE) { if (block.inputList[i].type === inputTypes.VALUE) {
const childBlock = block.inputList[i].connection.targetBlock(); const childBlock = block.inputList[i].connection.targetBlock();
if (childBlock) { if (childBlock) {
comment = this.allNestedComments(childBlock); comment = this.allNestedComments(childBlock);
@@ -245,15 +245,14 @@ Blockly.PHP.scrub_ = function(block, code, opt_thisOnly) {
/** /**
* Gets a property and adjusts the value while taking into account indexing. * Gets a property and adjusts the value while taking into account indexing.
* @param {!Blockly.Block} block The block. * @param {!Block} block The block.
* @param {string} atId The property ID of the element to get. * @param {string} atId The property ID of the element to get.
* @param {number=} opt_delta Value to add. * @param {number=} opt_delta Value to add.
* @param {boolean=} opt_negate Whether to negate the value. * @param {boolean=} opt_negate Whether to negate the value.
* @param {number=} opt_order The highest order acting on this value. * @param {number=} opt_order The highest order acting on this value.
* @return {string|number} * @return {string|number}
*/ */
Blockly.PHP.getAdjusted = function(block, atId, opt_delta, opt_negate, PHP.getAdjusted = function(block, atId, opt_delta, opt_negate, opt_order) {
opt_order) {
let delta = opt_delta || 0; let delta = opt_delta || 0;
let order = opt_order || this.ORDER_NONE; let order = opt_order || this.ORDER_NONE;
if (block.workspace.options.oneBasedIndex) { if (block.workspace.options.oneBasedIndex) {
@@ -274,7 +273,7 @@ Blockly.PHP.getAdjusted = function(block, atId, opt_delta, opt_negate,
} }
let at = this.valueToCode(block, atId, outerOrder) || defaultAtIndex; let at = this.valueToCode(block, atId, outerOrder) || defaultAtIndex;
if (Blockly.utils.string.isNumber(at)) { if (stringUtils.isNumber(at)) {
// If the index is a naked number, adjust it right now. // If the index is a naked number, adjust it right now.
at = Number(at) + delta; at = Number(at) + delta;
if (opt_negate) { if (opt_negate) {
@@ -302,3 +301,5 @@ Blockly.PHP.getAdjusted = function(block, atId, opt_delta, opt_negate,
} }
return at; return at;
}; };
exports = PHP;

View File

@@ -9,82 +9,67 @@
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.colour'); goog.module('Blockly.PHP.colour');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
Blockly.PHP['colour_picker'] = function(block) { PHP['colour_picker'] = function(block) {
// Colour picker. // Colour picker.
const code = Blockly.PHP.quote_(block.getFieldValue('COLOUR')); const code = PHP.quote_(block.getFieldValue('COLOUR'));
return [code, Blockly.PHP.ORDER_ATOMIC]; return [code, PHP.ORDER_ATOMIC];
}; };
Blockly.PHP['colour_random'] = function(block) { PHP['colour_random'] = function(block) {
// Generate a random colour. // Generate a random colour.
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('colour_random', [
'colour_random', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '() {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '() {', ' return \'#\' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), ' +
' return \'#\' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), ' + '6, \'0\', STR_PAD_LEFT);',
'6, \'0\', STR_PAD_LEFT);', '}'
'}']); ]);
const code = functionName + '()'; const code = functionName + '()';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['colour_rgb'] = function(block) { PHP['colour_rgb'] = function(block) {
// Compose a colour from RGB components expressed as percentages. // Compose a colour from RGB components expressed as percentages.
const red = Blockly.PHP.valueToCode(block, 'RED', const red = PHP.valueToCode(block, 'RED', PHP.ORDER_NONE) || 0;
Blockly.PHP.ORDER_NONE) || 0; const green = PHP.valueToCode(block, 'GREEN', PHP.ORDER_NONE) || 0;
const green = Blockly.PHP.valueToCode(block, 'GREEN', const blue = PHP.valueToCode(block, 'BLUE', PHP.ORDER_NONE) || 0;
Blockly.PHP.ORDER_NONE) || 0; const functionName = PHP.provideFunction_('colour_rgb', [
const blue = Blockly.PHP.valueToCode(block, 'BLUE', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($r, $g, $b) {',
Blockly.PHP.ORDER_NONE) || 0; ' $r = round(max(min($r, 100), 0) * 2.55);',
const functionName = Blockly.PHP.provideFunction_( ' $g = round(max(min($g, 100), 0) * 2.55);',
'colour_rgb', ' $b = round(max(min($b, 100), 0) * 2.55);', ' $hex = \'#\';',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' $hex .= str_pad(dechex($r), 2, \'0\', STR_PAD_LEFT);',
'($r, $g, $b) {', ' $hex .= str_pad(dechex($g), 2, \'0\', STR_PAD_LEFT);',
' $r = round(max(min($r, 100), 0) * 2.55);', ' $hex .= str_pad(dechex($b), 2, \'0\', STR_PAD_LEFT);', ' return $hex;',
' $g = round(max(min($g, 100), 0) * 2.55);', '}'
' $b = round(max(min($b, 100), 0) * 2.55);', ]);
' $hex = \'#\';',
' $hex .= str_pad(dechex($r), 2, \'0\', STR_PAD_LEFT);',
' $hex .= str_pad(dechex($g), 2, \'0\', STR_PAD_LEFT);',
' $hex .= str_pad(dechex($b), 2, \'0\', STR_PAD_LEFT);',
' return $hex;',
'}']);
const code = functionName + '(' + red + ', ' + green + ', ' + blue + ')'; const code = functionName + '(' + red + ', ' + green + ', ' + blue + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['colour_blend'] = function(block) { PHP['colour_blend'] = function(block) {
// Blend two colours together. // Blend two colours together.
const c1 = Blockly.PHP.valueToCode(block, 'COLOUR1', const c1 = PHP.valueToCode(block, 'COLOUR1', PHP.ORDER_NONE) || '\'#000000\'';
Blockly.PHP.ORDER_NONE) || '\'#000000\''; const c2 = PHP.valueToCode(block, 'COLOUR2', PHP.ORDER_NONE) || '\'#000000\'';
const c2 = Blockly.PHP.valueToCode(block, 'COLOUR2', const ratio = PHP.valueToCode(block, 'RATIO', PHP.ORDER_NONE) || 0.5;
Blockly.PHP.ORDER_NONE) || '\'#000000\''; const functionName = PHP.provideFunction_('colour_blend', [
const ratio = Blockly.PHP.valueToCode(block, 'RATIO', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($c1, $c2, $ratio) {',
Blockly.PHP.ORDER_NONE) || 0.5; ' $ratio = max(min($ratio, 1), 0);', ' $r1 = hexdec(substr($c1, 1, 2));',
const functionName = Blockly.PHP.provideFunction_( ' $g1 = hexdec(substr($c1, 3, 2));', ' $b1 = hexdec(substr($c1, 5, 2));',
'colour_blend', ' $r2 = hexdec(substr($c2, 1, 2));', ' $g2 = hexdec(substr($c2, 3, 2));',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' $b2 = hexdec(substr($c2, 5, 2));',
'($c1, $c2, $ratio) {', ' $r = round($r1 * (1 - $ratio) + $r2 * $ratio);',
' $ratio = max(min($ratio, 1), 0);', ' $g = round($g1 * (1 - $ratio) + $g2 * $ratio);',
' $r1 = hexdec(substr($c1, 1, 2));', ' $b = round($b1 * (1 - $ratio) + $b2 * $ratio);', ' $hex = \'#\';',
' $g1 = hexdec(substr($c1, 3, 2));', ' $hex .= str_pad(dechex($r), 2, \'0\', STR_PAD_LEFT);',
' $b1 = hexdec(substr($c1, 5, 2));', ' $hex .= str_pad(dechex($g), 2, \'0\', STR_PAD_LEFT);',
' $r2 = hexdec(substr($c2, 1, 2));', ' $hex .= str_pad(dechex($b), 2, \'0\', STR_PAD_LEFT);', ' return $hex;',
' $g2 = hexdec(substr($c2, 3, 2));', '}'
' $b2 = hexdec(substr($c2, 5, 2));', ]);
' $r = round($r1 * (1 - $ratio) + $r2 * $ratio);',
' $g = round($g1 * (1 - $ratio) + $g2 * $ratio);',
' $b = round($b1 * (1 - $ratio) + $b2 * $ratio);',
' $hex = \'#\';',
' $hex .= str_pad(dechex($r), 2, \'0\', STR_PAD_LEFT);',
' $hex .= str_pad(dechex($g), 2, \'0\', STR_PAD_LEFT);',
' $hex .= str_pad(dechex($b), 2, \'0\', STR_PAD_LEFT);',
' return $hex;',
'}']);
const code = functionName + '(' + c1 + ', ' + c2 + ', ' + ratio + ')'; const code = functionName + '(' + c1 + ', ' + c2 + ', ' + ratio + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };

View File

@@ -6,7 +6,6 @@
/** /**
* @fileoverview Generating PHP for list blocks. * @fileoverview Generating PHP for list blocks.
* @suppress {missingRequire}
*/ */
/** /**
@@ -21,77 +20,63 @@
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.lists'); goog.module('Blockly.PHP.lists');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
goog.require('Blockly.utils.string'); const stringUtils = goog.require('Blockly.utils.string');
const {NameType} = goog.require('Blockly.Names');
Blockly.PHP['lists_create_empty'] = function(block) { PHP['lists_create_empty'] = function(block) {
// Create an empty list. // Create an empty list.
return ['array()', Blockly.PHP.ORDER_FUNCTION_CALL]; return ['array()', PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_create_with'] = function(block) { PHP['lists_create_with'] = function(block) {
// Create a list with any number of elements of any type. // Create a list with any number of elements of any type.
let code = new Array(block.itemCount_); let code = new Array(block.itemCount_);
for (let i = 0; i < block.itemCount_; i++) { for (let i = 0; i < block.itemCount_; i++) {
code[i] = Blockly.PHP.valueToCode(block, 'ADD' + i, code[i] = PHP.valueToCode(block, 'ADD' + i, PHP.ORDER_NONE) || 'null';
Blockly.PHP.ORDER_NONE) || 'null';
} }
code = 'array(' + code.join(', ') + ')'; code = 'array(' + code.join(', ') + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_repeat'] = function(block) { PHP['lists_repeat'] = function(block) {
// Create a list with one element repeated. // Create a list with one element repeated.
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('lists_repeat', [
'lists_repeat', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value, $count) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' $array = array();', ' for ($index = 0; $index < $count; $index++) {',
'($value, $count) {', ' $array[] = $value;', ' }', ' return $array;', '}'
' $array = array();', ]);
' for ($index = 0; $index < $count; $index++) {', const element = PHP.valueToCode(block, 'ITEM', PHP.ORDER_NONE) || 'null';
' $array[] = $value;', const repeatCount = PHP.valueToCode(block, 'NUM', PHP.ORDER_NONE) || '0';
' }',
' return $array;',
'}']);
const element = Blockly.PHP.valueToCode(block, 'ITEM',
Blockly.PHP.ORDER_NONE) || 'null';
const repeatCount = Blockly.PHP.valueToCode(block, 'NUM',
Blockly.PHP.ORDER_NONE) || '0';
const code = functionName + '(' + element + ', ' + repeatCount + ')'; const code = functionName + '(' + element + ', ' + repeatCount + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_length'] = function(block) { PHP['lists_length'] = function(block) {
// String or array length. // String or array length.
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('length', [
'length', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value) {', ' if (is_string($value)) {', ' return strlen($value);', ' } else {',
' if (is_string($value)) {', ' return count($value);', ' }', '}'
' return strlen($value);', ]);
' } else {', const list = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '\'\'';
' return count($value);', return [functionName + '(' + list + ')', PHP.ORDER_FUNCTION_CALL];
' }',
'}']);
const list = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_NONE) || '\'\'';
return [functionName + '(' + list + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_isEmpty'] = function(block) { PHP['lists_isEmpty'] = function(block) {
// Is the string null or array empty? // Is the string null or array empty?
const argument0 = Blockly.PHP.valueToCode(block, 'VALUE', const argument0 =
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_FUNCTION_CALL) || 'array()';
return ['empty(' + argument0 + ')', Blockly.PHP.ORDER_FUNCTION_CALL]; return ['empty(' + argument0 + ')', PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_indexOf'] = function(block) { PHP['lists_indexOf'] = function(block) {
// Find an item in the list. // Find an item in the list.
const argument0 = Blockly.PHP.valueToCode(block, 'FIND', const argument0 = PHP.valueToCode(block, 'FIND', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\''; const argument1 = PHP.valueToCode(block, 'VALUE', PHP.ORDER_MEMBER) || '[]';
const argument1 = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_MEMBER) || '[]';
let errorIndex = ' -1'; let errorIndex = ' -1';
let indexAdjustment = ''; let indexAdjustment = '';
if (block.workspace.options.oneBasedIndex) { if (block.workspace.options.oneBasedIndex) {
@@ -101,144 +86,131 @@ Blockly.PHP['lists_indexOf'] = function(block) {
let functionName; let functionName;
if (block.getFieldValue('END') === 'FIRST') { if (block.getFieldValue('END') === 'FIRST') {
// indexOf // indexOf
functionName = Blockly.PHP.provideFunction_( functionName = PHP.provideFunction_('indexOf', [
'indexOf', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($haystack, $needle) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' for ($index = 0; $index < count($haystack); $index++) {',
'($haystack, $needle) {', ' if ($haystack[$index] == $needle) return $index' + indexAdjustment +
' for ($index = 0; $index < count($haystack); $index++) {', ';',
' if ($haystack[$index] == $needle) return $index' + ' }', ' return ' + errorIndex + ';', '}'
indexAdjustment + ';', ]);
' }',
' return ' + errorIndex + ';',
'}']);
} else { } else {
// lastIndexOf // lastIndexOf
functionName = Blockly.PHP.provideFunction_( functionName = PHP.provideFunction_('lastIndexOf', [
'lastIndexOf', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($haystack, $needle) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' $last = ' + errorIndex + ';',
'($haystack, $needle) {', ' for ($index = 0; $index < count($haystack); $index++) {',
' $last = ' + errorIndex + ';', ' if ($haystack[$index] == $needle) $last = $index' + indexAdjustment +
' for ($index = 0; $index < count($haystack); $index++) {', ';',
' if ($haystack[$index] == $needle) $last = $index' + ' }', ' return $last;', '}'
indexAdjustment + ';', ]);
' }',
' return $last;',
'}']);
} }
const code = functionName + '(' + argument1 + ', ' + argument0 + ')'; const code = functionName + '(' + argument1 + ', ' + argument0 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_getIndex'] = function(block) { PHP['lists_getIndex'] = function(block) {
// Get element at index. // Get element at index.
const mode = block.getFieldValue('MODE') || 'GET'; const mode = block.getFieldValue('MODE') || 'GET';
const where = block.getFieldValue('WHERE') || 'FROM_START'; const where = block.getFieldValue('WHERE') || 'FROM_START';
switch (where) { switch (where) {
case 'FIRST': case 'FIRST':
if (mode === 'GET') { if (mode === 'GET') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_MEMBER) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_MEMBER) || 'array()';
const code = list + '[0]'; const code = list + '[0]';
return [code, Blockly.PHP.ORDER_MEMBER]; return [code, PHP.ORDER_MEMBER];
} else if (mode === 'GET_REMOVE') { } else if (mode === 'GET_REMOVE') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
const code = 'array_shift(' + list + ')'; const code = 'array_shift(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} else if (mode === 'REMOVE') { } else if (mode === 'REMOVE') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
return 'array_shift(' + list + ');\n'; return 'array_shift(' + list + ');\n';
} }
break; break;
case 'LAST': case 'LAST':
if (mode === 'GET') { if (mode === 'GET') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
const code = 'end(' + list + ')'; const code = 'end(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} else if (mode === 'GET_REMOVE') { } else if (mode === 'GET_REMOVE') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
const code = 'array_pop(' + list + ')'; const code = 'array_pop(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} else if (mode === 'REMOVE') { } else if (mode === 'REMOVE') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
return 'array_pop(' + list + ');\n'; return 'array_pop(' + list + ');\n';
} }
break; break;
case 'FROM_START': { case 'FROM_START': {
const at = Blockly.PHP.getAdjusted(block, 'AT'); const at = PHP.getAdjusted(block, 'AT');
if (mode === 'GET') { if (mode === 'GET') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_MEMBER) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_MEMBER) || 'array()';
const code = list + '[' + at + ']'; const code = list + '[' + at + ']';
return [code, Blockly.PHP.ORDER_MEMBER]; return [code, PHP.ORDER_MEMBER];
} else if (mode === 'GET_REMOVE') { } else if (mode === 'GET_REMOVE') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
const code = 'array_splice(' + list + ', ' + at + ', 1)[0]'; const code = 'array_splice(' + list + ', ' + at + ', 1)[0]';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} else if (mode === 'REMOVE') { } else if (mode === 'REMOVE') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
return 'array_splice(' + list + ', ' + at + ', 1);\n'; return 'array_splice(' + list + ', ' + at + ', 1);\n';
} }
break; break;
} }
case 'FROM_END': case 'FROM_END':
if (mode === 'GET') { if (mode === 'GET') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
const at = Blockly.PHP.getAdjusted(block, 'AT', 1, true); const at = PHP.getAdjusted(block, 'AT', 1, true);
const code = 'array_slice(' + list + ', ' + at + ', 1)[0]'; const code = 'array_slice(' + list + ', ' + at + ', 1)[0]';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} else if (mode === 'GET_REMOVE' || mode === 'REMOVE') { } else if (mode === 'GET_REMOVE' || mode === 'REMOVE') {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
const at = Blockly.PHP.getAdjusted(block, 'AT', 1, false, const at =
Blockly.PHP.ORDER_SUBTRACTION); PHP.getAdjusted(block, 'AT', 1, false, PHP.ORDER_SUBTRACTION);
const code = 'array_splice(' + list + const code = 'array_splice(' + list + ', count(' + list + ') - ' + at +
', count(' + list + ') - ' + at + ', 1)[0]'; ', 1)[0]';
if (mode === 'GET_REMOVE') { if (mode === 'GET_REMOVE') {
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} else if (mode === 'REMOVE') { } else if (mode === 'REMOVE') {
return code + ';\n'; return code + ';\n';
} }
} }
break; break;
case 'RANDOM': { case 'RANDOM': {
const list = Blockly.PHP.valueToCode(block, 'VALUE', const list = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'array()';
Blockly.PHP.ORDER_NONE) || 'array()';
if (mode === 'GET') { if (mode === 'GET') {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('lists_get_random_item', [
'lists_get_random_item', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($list) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' return $list[rand(0,count($list)-1)];', '}'
'($list) {', ]);
' return $list[rand(0,count($list)-1)];',
'}']);
const code = functionName + '(' + list + ')'; const code = functionName + '(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} else if (mode === 'GET_REMOVE') { } else if (mode === 'GET_REMOVE') {
const functionName = Blockly.PHP.provideFunction_( const functionName =
'lists_get_remove_random_item', PHP.provideFunction_('lists_get_remove_random_item', [
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '(&$list) {',
'(&$list) {', ' $x = rand(0,count($list)-1);', ' unset($list[$x]);',
' $x = rand(0,count($list)-1);', ' return array_values($list);', '}'
' unset($list[$x]);', ]);
' return array_values($list);',
'}']);
const code = functionName + '(' + list + ')'; const code = functionName + '(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} else if (mode === 'REMOVE') { } else if (mode === 'REMOVE') {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('lists_remove_random_item', [
'lists_remove_random_item', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '(&$list) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' unset($list[rand(0,count($list)-1)]);', '}'
'(&$list) {', ]);
' unset($list[rand(0,count($list)-1)]);',
'}']);
return functionName + '(' + list + ');\n'; return functionName + '(' + list + ');\n';
} }
break; break;
@@ -247,13 +219,12 @@ Blockly.PHP['lists_getIndex'] = function(block) {
throw Error('Unhandled combination (lists_getIndex).'); throw Error('Unhandled combination (lists_getIndex).');
}; };
Blockly.PHP['lists_setIndex'] = function(block) { PHP['lists_setIndex'] = function(block) {
// Set element at index. // Set element at index.
// Note: Until February 2013 this block did not have MODE or WHERE inputs. // Note: Until February 2013 this block did not have MODE or WHERE inputs.
const mode = block.getFieldValue('MODE') || 'GET'; const mode = block.getFieldValue('MODE') || 'GET';
const where = block.getFieldValue('WHERE') || 'FROM_START'; const where = block.getFieldValue('WHERE') || 'FROM_START';
const value = Blockly.PHP.valueToCode(block, 'TO', const value = PHP.valueToCode(block, 'TO', PHP.ORDER_ASSIGNMENT) || 'null';
Blockly.PHP.ORDER_ASSIGNMENT) || 'null';
// Cache non-trivial values to variables to prevent repeated look-ups. // Cache non-trivial values to variables to prevent repeated look-ups.
// Closure, which accesses and modifies 'list'. // Closure, which accesses and modifies 'list'.
let cachedList; let cachedList;
@@ -261,8 +232,7 @@ Blockly.PHP['lists_setIndex'] = function(block) {
if (cachedList.match(/^\$\w+$/)) { if (cachedList.match(/^\$\w+$/)) {
return ''; return '';
} }
const listVar = Blockly.PHP.nameDB_.getDistinctName( const listVar = PHP.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
'tmp_list', Blockly.VARIABLE_CATEGORY_NAME);
const code = listVar + ' = &' + cachedList + ';\n'; const code = listVar + ' = &' + cachedList + ';\n';
cachedList = listVar; cachedList = listVar;
return code; return code;
@@ -270,25 +240,22 @@ Blockly.PHP['lists_setIndex'] = function(block) {
switch (where) { switch (where) {
case 'FIRST': case 'FIRST':
if (mode === 'SET') { if (mode === 'SET') {
const list = Blockly.PHP.valueToCode(block, 'LIST', const list =
Blockly.PHP.ORDER_MEMBER) || 'array()'; PHP.valueToCode(block, 'LIST', PHP.ORDER_MEMBER) || 'array()';
return list + '[0] = ' + value + ';\n'; return list + '[0] = ' + value + ';\n';
} else if (mode === 'INSERT') { } else if (mode === 'INSERT') {
const list = Blockly.PHP.valueToCode(block, 'LIST', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()';
return 'array_unshift(' + list + ', ' + value + ');\n'; return 'array_unshift(' + list + ', ' + value + ');\n';
} }
break; break;
case 'LAST': { case 'LAST': {
const list = Blockly.PHP.valueToCode(block, 'LIST', const list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()';
Blockly.PHP.ORDER_NONE) || 'array()';
if (mode === 'SET') { if (mode === 'SET') {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('lists_set_last_item', [
'lists_set_last_item', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '(&$list, $value) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' $list[count($list) - 1] = $value;', '}'
'(&$list, $value) {', ]);
' $list[count($list) - 1] = $value;',
'}']);
return functionName + '(' + list + ', ' + value + ');\n'; return functionName + '(' + list + ', ' + value + ');\n';
} else if (mode === 'INSERT') { } else if (mode === 'INSERT') {
return 'array_push(' + list + ', ' + value + ');\n'; return 'array_push(' + list + ', ' + value + ');\n';
@@ -296,55 +263,50 @@ Blockly.PHP['lists_setIndex'] = function(block) {
break; break;
} }
case 'FROM_START': { case 'FROM_START': {
const at = Blockly.PHP.getAdjusted(block, 'AT'); const at = PHP.getAdjusted(block, 'AT');
if (mode === 'SET') { if (mode === 'SET') {
const list = Blockly.PHP.valueToCode(block, 'LIST', const list =
Blockly.PHP.ORDER_MEMBER) || 'array()'; PHP.valueToCode(block, 'LIST', PHP.ORDER_MEMBER) || 'array()';
return list + '[' + at + '] = ' + value + ';\n'; return list + '[' + at + '] = ' + value + ';\n';
} else if (mode === 'INSERT') { } else if (mode === 'INSERT') {
const list = Blockly.PHP.valueToCode(block, 'LIST', const list =
Blockly.PHP.ORDER_NONE) || 'array()'; PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()';
return 'array_splice(' + list + ', ' + at + ', 0, ' + value + ');\n'; return 'array_splice(' + list + ', ' + at + ', 0, ' + value + ');\n';
} }
break; break;
} }
case 'FROM_END': { case 'FROM_END': {
const list = Blockly.PHP.valueToCode(block, 'LIST', const list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()';
Blockly.PHP.ORDER_NONE) || 'array()'; const at = PHP.getAdjusted(block, 'AT', 1);
const at = Blockly.PHP.getAdjusted(block, 'AT', 1);
if (mode === 'SET') { if (mode === 'SET') {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('lists_set_from_end', [
'lists_set_from_end', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ +
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '(&$list, $at, $value) {',
'(&$list, $at, $value) {', ' $list[count($list) - $at] = $value;', '}'
' $list[count($list) - $at] = $value;', ]);
'}']);
return functionName + '(' + list + ', ' + at + ', ' + value + ');\n'; return functionName + '(' + list + ', ' + at + ', ' + value + ');\n';
} else if (mode === 'INSERT') { } else if (mode === 'INSERT') {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('lists_insert_from_end', [
'lists_insert_from_end', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ +
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '(&$list, $at, $value) {',
'(&$list, $at, $value) {', ' return array_splice($list, count($list) - $at, 0, $value);', '}'
' return array_splice($list, count($list) - $at, 0, $value);', ]);
'}']);
return functionName + '(' + list + ', ' + at + ', ' + value + ');\n'; return functionName + '(' + list + ', ' + at + ', ' + value + ');\n';
} }
break; break;
} }
case 'RANDOM': case 'RANDOM':
cachedList = Blockly.PHP.valueToCode(block, 'LIST', cachedList =
Blockly.PHP.ORDER_REFERENCE) || 'array()'; PHP.valueToCode(block, 'LIST', PHP.ORDER_REFERENCE) || 'array()';
let code = cacheList(); let code = cacheList();
const list = cachedList; const list = cachedList;
const xVar = Blockly.PHP.nameDB_.getDistinctName( const xVar = PHP.nameDB_.getDistinctName('tmp_x', NameType.VARIABLE);
'tmp_x', Blockly.VARIABLE_CATEGORY_NAME);
code += xVar + ' = rand(0, count(' + list + ')-1);\n'; code += xVar + ' = rand(0, count(' + list + ')-1);\n';
if (mode === 'SET') { if (mode === 'SET') {
code += list + '[' + xVar + '] = ' + value + ';\n'; code += list + '[' + xVar + '] = ' + value + ';\n';
return code; return code;
} else if (mode === 'INSERT') { } else if (mode === 'INSERT') {
code += 'array_splice(' + list + ', ' + xVar + ', 0, ' + value + code += 'array_splice(' + list + ', ' + xVar + ', 0, ' + value + ');\n';
');\n';
return code; return code;
} }
break; break;
@@ -352,27 +314,26 @@ Blockly.PHP['lists_setIndex'] = function(block) {
throw Error('Unhandled combination (lists_setIndex).'); throw Error('Unhandled combination (lists_setIndex).');
}; };
Blockly.PHP['lists_getSublist'] = function(block) { PHP['lists_getSublist'] = function(block) {
// Get sublist. // Get sublist.
const list = Blockly.PHP.valueToCode(block, 'LIST', const list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()';
Blockly.PHP.ORDER_NONE) || 'array()';
const where1 = block.getFieldValue('WHERE1'); const where1 = block.getFieldValue('WHERE1');
const where2 = block.getFieldValue('WHERE2'); const where2 = block.getFieldValue('WHERE2');
let code; let code;
if (where1 === 'FIRST' && where2 === 'LAST') { if (where1 === 'FIRST' && where2 === 'LAST') {
code = list; code = list;
} else if (list.match(/^\$\w+$/) || } else if (
list.match(/^\$\w+$/) ||
(where1 !== 'FROM_END' && where2 === 'FROM_START')) { (where1 !== 'FROM_END' && where2 === 'FROM_START')) {
// If the list is a simple value or doesn't require a call for length, don't // If the list is a simple value or doesn't require a call for length, don't
// generate a helper function. // generate a helper function.
let at1; let at1;
switch (where1) { switch (where1) {
case 'FROM_START': case 'FROM_START':
at1 = Blockly.PHP.getAdjusted(block, 'AT1'); at1 = PHP.getAdjusted(block, 'AT1');
break; break;
case 'FROM_END': case 'FROM_END':
at1 = Blockly.PHP.getAdjusted(block, 'AT1', 1, false, at1 = PHP.getAdjusted(block, 'AT1', 1, false, PHP.ORDER_SUBTRACTION);
Blockly.PHP.ORDER_SUBTRACTION);
at1 = 'count(' + list + ') - ' + at1; at1 = 'count(' + list + ') - ' + at1;
break; break;
case 'FIRST': case 'FIRST':
@@ -385,10 +346,10 @@ Blockly.PHP['lists_getSublist'] = function(block) {
let length; let length;
switch (where2) { switch (where2) {
case 'FROM_START': case 'FROM_START':
at2 = Blockly.PHP.getAdjusted(block, 'AT2', 0, false, at2 = PHP.getAdjusted(block, 'AT2', 0, false, PHP.ORDER_SUBTRACTION);
Blockly.PHP.ORDER_SUBTRACTION);
length = at2 + ' - '; length = at2 + ' - ';
if (Blockly.utils.string.isNumber(String(at1)) || String(at1).match(/^\(.+\)$/)) { if (stringUtils.isNumber(String(at1)) ||
String(at1).match(/^\(.+\)$/)) {
length += at1; length += at1;
} else { } else {
length += '(' + at1 + ')'; length += '(' + at1 + ')';
@@ -396,10 +357,10 @@ Blockly.PHP['lists_getSublist'] = function(block) {
length += ' + 1'; length += ' + 1';
break; break;
case 'FROM_END': case 'FROM_END':
at2 = Blockly.PHP.getAdjusted(block, 'AT2', 0, false, at2 = PHP.getAdjusted(block, 'AT2', 0, false, PHP.ORDER_SUBTRACTION);
Blockly.PHP.ORDER_SUBTRACTION);
length = 'count(' + list + ') - ' + at2 + ' - '; length = 'count(' + list + ') - ' + at2 + ' - ';
if (Blockly.utils.string.isNumber(String(at1)) || String(at1).match(/^\(.+\)$/)) { if (stringUtils.isNumber(String(at1)) ||
String(at1).match(/^\(.+\)$/)) {
length += at1; length += at1;
} else { } else {
length += '(' + at1 + ')'; length += '(' + at1 + ')';
@@ -407,7 +368,8 @@ Blockly.PHP['lists_getSublist'] = function(block) {
break; break;
case 'LAST': case 'LAST':
length = 'count(' + list + ') - '; length = 'count(' + list + ') - ';
if (Blockly.utils.string.isNumber(String(at1)) || String(at1).match(/^\(.+\)$/)) { if (stringUtils.isNumber(String(at1)) ||
String(at1).match(/^\(.+\)$/)) {
length += at1; length += at1;
} else { } else {
length += '(' + at1 + ')'; length += '(' + at1 + ')';
@@ -418,71 +380,61 @@ Blockly.PHP['lists_getSublist'] = function(block) {
} }
code = 'array_slice(' + list + ', ' + at1 + ', ' + length + ')'; code = 'array_slice(' + list + ', ' + at1 + ', ' + length + ')';
} else { } else {
const at1 = Blockly.PHP.getAdjusted(block, 'AT1'); const at1 = PHP.getAdjusted(block, 'AT1');
const at2 = Blockly.PHP.getAdjusted(block, 'AT2'); const at2 = PHP.getAdjusted(block, 'AT2');
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('lists_get_sublist', [
'lists_get_sublist', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ +
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($list, $where1, $at1, $where2, $at2) {',
'($list, $where1, $at1, $where2, $at2) {', ' if ($where1 == \'FROM_END\') {',
' if ($where1 == \'FROM_END\') {', ' $at1 = count($list) - 1 - $at1;',
' $at1 = count($list) - 1 - $at1;', ' } else if ($where1 == \'FIRST\') {',
' } else if ($where1 == \'FIRST\') {', ' $at1 = 0;',
' $at1 = 0;', ' } else if ($where1 != \'FROM_START\') {',
' } else if ($where1 != \'FROM_START\') {', ' throw new Exception(\'Unhandled option (lists_get_sublist).\');',
' throw new Exception(\'Unhandled option (lists_get_sublist).\');', ' }',
' }', ' $length = 0;',
' $length = 0;', ' if ($where2 == \'FROM_START\') {',
' if ($where2 == \'FROM_START\') {', ' $length = $at2 - $at1 + 1;',
' $length = $at2 - $at1 + 1;', ' } else if ($where2 == \'FROM_END\') {',
' } else if ($where2 == \'FROM_END\') {', ' $length = count($list) - $at1 - $at2;',
' $length = count($list) - $at1 - $at2;', ' } else if ($where2 == \'LAST\') {',
' } else if ($where2 == \'LAST\') {', ' $length = count($list) - $at1;',
' $length = count($list) - $at1;', ' } else {',
' } else {', ' throw new Exception(\'Unhandled option (lists_get_sublist).\');',
' throw new Exception(\'Unhandled option (lists_get_sublist).\');', ' }',
' }', ' return array_slice($list, $at1, $length);',
' return array_slice($list, $at1, $length);', '}'
'}']); ]);
code = functionName + '(' + list + ', \'' + code = functionName + '(' + list + ', \'' + where1 + '\', ' + at1 + ', \'' +
where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')'; where2 + '\', ' + at2 + ')';
} }
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_sort'] = function(block) { PHP['lists_sort'] = function(block) {
// Block for sorting a list. // Block for sorting a list.
const listCode = Blockly.PHP.valueToCode(block, 'LIST', const listCode = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()';
Blockly.PHP.ORDER_NONE) || 'array()';
const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1; const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1;
const type = block.getFieldValue('TYPE'); const type = block.getFieldValue('TYPE');
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('lists_sort', [
'lists_sort', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ +
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($list, $type, $direction) {',
'($list, $type, $direction) {', ' $sortCmpFuncs = array(', ' "NUMERIC" => "strnatcasecmp",',
' $sortCmpFuncs = array(', ' "TEXT" => "strcmp",', ' "IGNORE_CASE" => "strcasecmp"', ' );',
' "NUMERIC" => "strnatcasecmp",', ' $sortCmp = $sortCmpFuncs[$type];',
' "TEXT" => "strcmp",', ' $list2 = $list;', // Clone list.
' "IGNORE_CASE" => "strcasecmp"', ' usort($list2, $sortCmp);', ' if ($direction == -1) {',
' );', ' $list2 = array_reverse($list2);', ' }', ' return $list2;', '}'
' $sortCmp = $sortCmpFuncs[$type];', ]);
' $list2 = $list;', // Clone list. const sortCode =
' usort($list2, $sortCmp);', functionName + '(' + listCode + ', "' + type + '", ' + direction + ')';
' if ($direction == -1) {', return [sortCode, PHP.ORDER_FUNCTION_CALL];
' $list2 = array_reverse($list2);',
' }',
' return $list2;',
'}']);
const sortCode = functionName +
'(' + listCode + ', "' + type + '", ' + direction + ')';
return [sortCode, Blockly.PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_split'] = function(block) { PHP['lists_split'] = function(block) {
// Block for splitting text into a list, or joining a list into text. // Block for splitting text into a list, or joining a list into text.
let value_input = Blockly.PHP.valueToCode(block, 'INPUT', let value_input = PHP.valueToCode(block, 'INPUT', PHP.ORDER_NONE);
Blockly.PHP.ORDER_NONE); const value_delim = PHP.valueToCode(block, 'DELIM', PHP.ORDER_NONE) || '\'\'';
const value_delim = Blockly.PHP.valueToCode(block, 'DELIM',
Blockly.PHP.ORDER_NONE) || '\'\'';
const mode = block.getFieldValue('MODE'); const mode = block.getFieldValue('MODE');
let functionName; let functionName;
if (mode === 'SPLIT') { if (mode === 'SPLIT') {
@@ -499,13 +451,12 @@ Blockly.PHP['lists_split'] = function(block) {
throw Error('Unknown mode: ' + mode); throw Error('Unknown mode: ' + mode);
} }
const code = functionName + '(' + value_delim + ', ' + value_input + ')'; const code = functionName + '(' + value_delim + ', ' + value_input + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['lists_reverse'] = function(block) { PHP['lists_reverse'] = function(block) {
// Block for reversing a list. // Block for reversing a list.
const list = Blockly.PHP.valueToCode(block, 'LIST', const list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]';
Blockly.PHP.ORDER_NONE) || '[]';
const code = 'array_reverse(' + list + ')'; const code = 'array_reverse(' + list + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };

View File

@@ -9,73 +9,66 @@
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.logic'); goog.module('Blockly.PHP.logic');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
Blockly.PHP['controls_if'] = function(block) { PHP['controls_if'] = function(block) {
// If/elseif/else condition. // If/elseif/else condition.
let n = 0; let n = 0;
let code = '', branchCode, conditionCode; let code = '', branchCode, conditionCode;
if (Blockly.PHP.STATEMENT_PREFIX) { if (PHP.STATEMENT_PREFIX) {
// Automatic prefix insertion is switched off for this block. Add manually. // Automatic prefix insertion is switched off for this block. Add manually.
code += Blockly.PHP.injectId(Blockly.PHP.STATEMENT_PREFIX, block); code += PHP.injectId(PHP.STATEMENT_PREFIX, block);
} }
do { do {
conditionCode = Blockly.PHP.valueToCode(block, 'IF' + n, conditionCode = PHP.valueToCode(block, 'IF' + n, PHP.ORDER_NONE) || 'false';
Blockly.PHP.ORDER_NONE) || 'false'; branchCode = PHP.statementToCode(block, 'DO' + n);
branchCode = Blockly.PHP.statementToCode(block, 'DO' + n); if (PHP.STATEMENT_SUFFIX) {
if (Blockly.PHP.STATEMENT_SUFFIX) { branchCode = PHP.prefixLines(
branchCode = Blockly.PHP.prefixLines( PHP.injectId(PHP.STATEMENT_SUFFIX, block), PHP.INDENT) +
Blockly.PHP.injectId(Blockly.PHP.STATEMENT_SUFFIX, block), branchCode;
Blockly.PHP.INDENT) + branchCode;
} }
code += (n > 0 ? ' else ' : '') + code += (n > 0 ? ' else ' : '') + 'if (' + conditionCode + ') {\n' +
'if (' + conditionCode + ') {\n' + branchCode + '}'; branchCode + '}';
n++; n++;
} while (block.getInput('IF' + n)); } while (block.getInput('IF' + n));
if (block.getInput('ELSE') || Blockly.PHP.STATEMENT_SUFFIX) { if (block.getInput('ELSE') || PHP.STATEMENT_SUFFIX) {
branchCode = Blockly.PHP.statementToCode(block, 'ELSE'); branchCode = PHP.statementToCode(block, 'ELSE');
if (Blockly.PHP.STATEMENT_SUFFIX) { if (PHP.STATEMENT_SUFFIX) {
branchCode = Blockly.PHP.prefixLines( branchCode = PHP.prefixLines(
Blockly.PHP.injectId(Blockly.PHP.STATEMENT_SUFFIX, block), PHP.injectId(PHP.STATEMENT_SUFFIX, block), PHP.INDENT) +
Blockly.PHP.INDENT) + branchCode; branchCode;
} }
code += ' else {\n' + branchCode + '}'; code += ' else {\n' + branchCode + '}';
} }
return code + '\n'; return code + '\n';
}; };
Blockly.PHP['controls_ifelse'] = Blockly.PHP['controls_if']; PHP['controls_ifelse'] = PHP['controls_if'];
Blockly.PHP['logic_compare'] = function(block) { PHP['logic_compare'] = function(block) {
// Comparison operator. // Comparison operator.
const OPERATORS = { const OPERATORS =
'EQ': '==', {'EQ': '==', 'NEQ': '!=', 'LT': '<', 'LTE': '<=', 'GT': '>', 'GTE': '>='};
'NEQ': '!=',
'LT': '<',
'LTE': '<=',
'GT': '>',
'GTE': '>='
};
const operator = OPERATORS[block.getFieldValue('OP')]; const operator = OPERATORS[block.getFieldValue('OP')];
const order = (operator === '==' || operator === '!=') ? const order = (operator === '==' || operator === '!=') ? PHP.ORDER_EQUALITY :
Blockly.PHP.ORDER_EQUALITY : Blockly.PHP.ORDER_RELATIONAL; PHP.ORDER_RELATIONAL;
const argument0 = Blockly.PHP.valueToCode(block, 'A', order) || '0'; const argument0 = PHP.valueToCode(block, 'A', order) || '0';
const argument1 = Blockly.PHP.valueToCode(block, 'B', order) || '0'; const argument1 = PHP.valueToCode(block, 'B', order) || '0';
const code = argument0 + ' ' + operator + ' ' + argument1; const code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order]; return [code, order];
}; };
Blockly.PHP['logic_operation'] = function(block) { PHP['logic_operation'] = function(block) {
// Operations 'and', 'or'. // Operations 'and', 'or'.
const operator = (block.getFieldValue('OP') === 'AND') ? '&&' : '||'; const operator = (block.getFieldValue('OP') === 'AND') ? '&&' : '||';
const order = (operator === '&&') ? Blockly.PHP.ORDER_LOGICAL_AND : const order =
Blockly.PHP.ORDER_LOGICAL_OR; (operator === '&&') ? PHP.ORDER_LOGICAL_AND : PHP.ORDER_LOGICAL_OR;
let argument0 = Blockly.PHP.valueToCode(block, 'A', order); let argument0 = PHP.valueToCode(block, 'A', order);
let argument1 = Blockly.PHP.valueToCode(block, 'B', order); let argument1 = PHP.valueToCode(block, 'B', order);
if (!argument0 && !argument1) { if (!argument0 && !argument1) {
// If there are no arguments, then the return value is false. // If there are no arguments, then the return value is false.
argument0 = 'false'; argument0 = 'false';
@@ -94,34 +87,33 @@ Blockly.PHP['logic_operation'] = function(block) {
return [code, order]; return [code, order];
}; };
Blockly.PHP['logic_negate'] = function(block) { PHP['logic_negate'] = function(block) {
// Negation. // Negation.
const order = Blockly.PHP.ORDER_LOGICAL_NOT; const order = PHP.ORDER_LOGICAL_NOT;
const argument0 = Blockly.PHP.valueToCode(block, 'BOOL', order) || const argument0 = PHP.valueToCode(block, 'BOOL', order) || 'true';
'true';
const code = '!' + argument0; const code = '!' + argument0;
return [code, order]; return [code, order];
}; };
Blockly.PHP['logic_boolean'] = function(block) { PHP['logic_boolean'] = function(block) {
// Boolean values true and false. // Boolean values true and false.
const code = (block.getFieldValue('BOOL') === 'TRUE') ? 'true' : 'false'; const code = (block.getFieldValue('BOOL') === 'TRUE') ? 'true' : 'false';
return [code, Blockly.PHP.ORDER_ATOMIC]; return [code, PHP.ORDER_ATOMIC];
}; };
Blockly.PHP['logic_null'] = function(block) { PHP['logic_null'] = function(block) {
// Null data type. // Null data type.
return ['null', Blockly.PHP.ORDER_ATOMIC]; return ['null', PHP.ORDER_ATOMIC];
}; };
Blockly.PHP['logic_ternary'] = function(block) { PHP['logic_ternary'] = function(block) {
// Ternary operator. // Ternary operator.
const value_if = Blockly.PHP.valueToCode(block, 'IF', const value_if =
Blockly.PHP.ORDER_CONDITIONAL) || 'false'; PHP.valueToCode(block, 'IF', PHP.ORDER_CONDITIONAL) || 'false';
const value_then = Blockly.PHP.valueToCode(block, 'THEN', const value_then =
Blockly.PHP.ORDER_CONDITIONAL) || 'null'; PHP.valueToCode(block, 'THEN', PHP.ORDER_CONDITIONAL) || 'null';
const value_else = Blockly.PHP.valueToCode(block, 'ELSE', const value_else =
Blockly.PHP.ORDER_CONDITIONAL) || 'null'; PHP.valueToCode(block, 'ELSE', PHP.ORDER_CONDITIONAL) || 'null';
const code = value_if + ' ? ' + value_then + ' : ' + value_else; const code = value_if + ' ? ' + value_then + ' : ' + value_else;
return [code, Blockly.PHP.ORDER_CONDITIONAL]; return [code, PHP.ORDER_CONDITIONAL];
}; };

View File

@@ -6,17 +6,17 @@
/** /**
* @fileoverview Generating PHP for loop blocks. * @fileoverview Generating PHP for loop blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.loops'); goog.module('Blockly.PHP.loops');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
goog.require('Blockly.utils.string'); const stringUtils = goog.require('Blockly.utils.string');
const {NameType} = goog.require('Blockly.Names');
Blockly.PHP['controls_repeat_ext'] = function(block) { PHP['controls_repeat_ext'] = function(block) {
// Repeat n times. // Repeat n times.
let repeats; let repeats;
if (block.getField('TIMES')) { if (block.getField('TIMES')) {
@@ -24,63 +24,55 @@ Blockly.PHP['controls_repeat_ext'] = function(block) {
repeats = String(Number(block.getFieldValue('TIMES'))); repeats = String(Number(block.getFieldValue('TIMES')));
} else { } else {
// External number. // External number.
repeats = Blockly.PHP.valueToCode(block, 'TIMES', repeats = PHP.valueToCode(block, 'TIMES', PHP.ORDER_ASSIGNMENT) || '0';
Blockly.PHP.ORDER_ASSIGNMENT) || '0';
} }
let branch = Blockly.PHP.statementToCode(block, 'DO'); let branch = PHP.statementToCode(block, 'DO');
branch = Blockly.PHP.addLoopTrap(branch, block); branch = PHP.addLoopTrap(branch, block);
let code = ''; let code = '';
const loopVar = Blockly.PHP.nameDB_.getDistinctName( const loopVar = PHP.nameDB_.getDistinctName('count', NameType.VARIABLE);
'count', Blockly.VARIABLE_CATEGORY_NAME);
let endVar = repeats; let endVar = repeats;
if (!repeats.match(/^\w+$/) && !Blockly.utils.string.isNumber(repeats)) { if (!repeats.match(/^\w+$/) && !stringUtils.isNumber(repeats)) {
endVar = Blockly.PHP.nameDB_.getDistinctName( endVar = PHP.nameDB_.getDistinctName('repeat_end', NameType.VARIABLE);
'repeat_end', Blockly.VARIABLE_CATEGORY_NAME);
code += endVar + ' = ' + repeats + ';\n'; code += endVar + ' = ' + repeats + ';\n';
} }
code += 'for (' + loopVar + ' = 0; ' + code += 'for (' + loopVar + ' = 0; ' + loopVar + ' < ' + endVar + '; ' +
loopVar + ' < ' + endVar + '; ' + loopVar + '++) {\n' + branch + '}\n';
loopVar + '++) {\n' +
branch + '}\n';
return code; return code;
}; };
Blockly.PHP['controls_repeat'] = Blockly.PHP['controls_repeat_ext']; PHP['controls_repeat'] = PHP['controls_repeat_ext'];
Blockly.PHP['controls_whileUntil'] = function(block) { PHP['controls_whileUntil'] = function(block) {
// Do while/until loop. // Do while/until loop.
const until = block.getFieldValue('MODE') === 'UNTIL'; const until = block.getFieldValue('MODE') === 'UNTIL';
let argument0 = Blockly.PHP.valueToCode(block, 'BOOL', let argument0 =
until ? Blockly.PHP.ORDER_LOGICAL_NOT : PHP.valueToCode(
Blockly.PHP.ORDER_NONE) || 'false'; block, 'BOOL', until ? PHP.ORDER_LOGICAL_NOT : PHP.ORDER_NONE) ||
let branch = Blockly.PHP.statementToCode(block, 'DO'); 'false';
branch = Blockly.PHP.addLoopTrap(branch, block); let branch = PHP.statementToCode(block, 'DO');
branch = PHP.addLoopTrap(branch, block);
if (until) { if (until) {
argument0 = '!' + argument0; argument0 = '!' + argument0;
} }
return 'while (' + argument0 + ') {\n' + branch + '}\n'; return 'while (' + argument0 + ') {\n' + branch + '}\n';
}; };
Blockly.PHP['controls_for'] = function(block) { PHP['controls_for'] = function(block) {
// For loop. // For loop.
const variable0 = Blockly.PHP.nameDB_.getName( const variable0 =
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME); PHP.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
const argument0 = Blockly.PHP.valueToCode(block, 'FROM', const argument0 = PHP.valueToCode(block, 'FROM', PHP.ORDER_ASSIGNMENT) || '0';
Blockly.PHP.ORDER_ASSIGNMENT) || '0'; const argument1 = PHP.valueToCode(block, 'TO', PHP.ORDER_ASSIGNMENT) || '0';
const argument1 = Blockly.PHP.valueToCode(block, 'TO', const increment = PHP.valueToCode(block, 'BY', PHP.ORDER_ASSIGNMENT) || '1';
Blockly.PHP.ORDER_ASSIGNMENT) || '0'; let branch = PHP.statementToCode(block, 'DO');
const increment = Blockly.PHP.valueToCode(block, 'BY', branch = PHP.addLoopTrap(branch, block);
Blockly.PHP.ORDER_ASSIGNMENT) || '1';
let branch = Blockly.PHP.statementToCode(block, 'DO');
branch = Blockly.PHP.addLoopTrap(branch, block);
let code; let code;
if (Blockly.utils.string.isNumber(argument0) && Blockly.utils.string.isNumber(argument1) && if (stringUtils.isNumber(argument0) && stringUtils.isNumber(argument1) &&
Blockly.utils.string.isNumber(increment)) { stringUtils.isNumber(increment)) {
// All arguments are simple numbers. // All arguments are simple numbers.
const up = Number(argument0) <= Number(argument1); const up = Number(argument0) <= Number(argument1);
code = 'for (' + variable0 + ' = ' + argument0 + '; ' + code = 'for (' + variable0 + ' = ' + argument0 + '; ' + variable0 +
variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' + (up ? ' <= ' : ' >= ') + argument1 + '; ' + variable0;
variable0;
const step = Math.abs(Number(increment)); const step = Math.abs(Number(increment));
if (step === 1) { if (step === 1) {
code += up ? '++' : '--'; code += up ? '++' : '--';
@@ -92,73 +84,71 @@ Blockly.PHP['controls_for'] = function(block) {
code = ''; code = '';
// Cache non-trivial values to variables to prevent repeated look-ups. // Cache non-trivial values to variables to prevent repeated look-ups.
let startVar = argument0; let startVar = argument0;
if (!argument0.match(/^\w+$/) && !Blockly.utils.string.isNumber(argument0)) { if (!argument0.match(/^\w+$/) && !stringUtils.isNumber(argument0)) {
startVar = Blockly.PHP.nameDB_.getDistinctName( startVar =
variable0 + '_start', Blockly.VARIABLE_CATEGORY_NAME); PHP.nameDB_.getDistinctName(variable0 + '_start', NameType.VARIABLE);
code += startVar + ' = ' + argument0 + ';\n'; code += startVar + ' = ' + argument0 + ';\n';
} }
let endVar = argument1; let endVar = argument1;
if (!argument1.match(/^\w+$/) && !Blockly.utils.string.isNumber(argument1)) { if (!argument1.match(/^\w+$/) && !stringUtils.isNumber(argument1)) {
endVar = Blockly.PHP.nameDB_.getDistinctName( endVar =
variable0 + '_end', Blockly.VARIABLE_CATEGORY_NAME); PHP.nameDB_.getDistinctName(variable0 + '_end', NameType.VARIABLE);
code += endVar + ' = ' + argument1 + ';\n'; code += endVar + ' = ' + argument1 + ';\n';
} }
// Determine loop direction at start, in case one of the bounds // Determine loop direction at start, in case one of the bounds
// changes during loop execution. // changes during loop execution.
const incVar = Blockly.PHP.nameDB_.getDistinctName( const incVar =
variable0 + '_inc', Blockly.VARIABLE_CATEGORY_NAME); PHP.nameDB_.getDistinctName(variable0 + '_inc', NameType.VARIABLE);
code += incVar + ' = '; code += incVar + ' = ';
if (Blockly.utils.string.isNumber(increment)) { if (stringUtils.isNumber(increment)) {
code += Math.abs(increment) + ';\n'; code += Math.abs(increment) + ';\n';
} else { } else {
code += 'abs(' + increment + ');\n'; code += 'abs(' + increment + ');\n';
} }
code += 'if (' + startVar + ' > ' + endVar + ') {\n'; code += 'if (' + startVar + ' > ' + endVar + ') {\n';
code += Blockly.PHP.INDENT + incVar + ' = -' + incVar + ';\n'; code += PHP.INDENT + incVar + ' = -' + incVar + ';\n';
code += '}\n'; code += '}\n';
code += 'for (' + variable0 + ' = ' + startVar + '; ' + code += 'for (' + variable0 + ' = ' + startVar + '; ' + incVar +
incVar + ' >= 0 ? ' + ' >= 0 ? ' + variable0 + ' <= ' + endVar + ' : ' + variable0 +
variable0 + ' <= ' + endVar + ' : ' + ' >= ' + endVar + '; ' + variable0 + ' += ' + incVar + ') {\n' +
variable0 + ' >= ' + endVar + '; ' +
variable0 + ' += ' + incVar + ') {\n' +
branch + '}\n'; branch + '}\n';
} }
return code; return code;
}; };
Blockly.PHP['controls_forEach'] = function(block) { PHP['controls_forEach'] = function(block) {
// For each loop. // For each loop.
const variable0 = Blockly.PHP.nameDB_.getName( const variable0 =
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME); PHP.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
const argument0 = Blockly.PHP.valueToCode(block, 'LIST', const argument0 =
Blockly.PHP.ORDER_ASSIGNMENT) || '[]'; PHP.valueToCode(block, 'LIST', PHP.ORDER_ASSIGNMENT) || '[]';
let branch = Blockly.PHP.statementToCode(block, 'DO'); let branch = PHP.statementToCode(block, 'DO');
branch = Blockly.PHP.addLoopTrap(branch, block); branch = PHP.addLoopTrap(branch, block);
let code = ''; let code = '';
code += 'foreach (' + argument0 + ' as ' + variable0 + code +=
') {\n' + branch + '}\n'; 'foreach (' + argument0 + ' as ' + variable0 + ') {\n' + branch + '}\n';
return code; return code;
}; };
Blockly.PHP['controls_flow_statements'] = function(block) { PHP['controls_flow_statements'] = function(block) {
// Flow statements: continue, break. // Flow statements: continue, break.
let xfix = ''; let xfix = '';
if (Blockly.PHP.STATEMENT_PREFIX) { if (PHP.STATEMENT_PREFIX) {
// Automatic prefix insertion is switched off for this block. Add manually. // Automatic prefix insertion is switched off for this block. Add manually.
xfix += Blockly.PHP.injectId(Blockly.PHP.STATEMENT_PREFIX, block); xfix += PHP.injectId(PHP.STATEMENT_PREFIX, block);
} }
if (Blockly.PHP.STATEMENT_SUFFIX) { if (PHP.STATEMENT_SUFFIX) {
// Inject any statement suffix here since the regular one at the end // Inject any statement suffix here since the regular one at the end
// will not get executed if the break/continue is triggered. // will not get executed if the break/continue is triggered.
xfix += Blockly.PHP.injectId(Blockly.PHP.STATEMENT_SUFFIX, block); xfix += PHP.injectId(PHP.STATEMENT_SUFFIX, block);
} }
if (Blockly.PHP.STATEMENT_PREFIX) { if (PHP.STATEMENT_PREFIX) {
const loop = block.getSurroundLoop(); const loop = block.getSurroundLoop();
if (loop && !loop.suppressPrefixSuffix) { if (loop && !loop.suppressPrefixSuffix) {
// Inject loop's statement prefix here since the regular one at the end // Inject loop's statement prefix here since the regular one at the end
// of the loop will not get executed if 'continue' is triggered. // of the loop will not get executed if 'continue' is triggered.
// In the case of 'break', a prefix is needed due to the loop's suffix. // In the case of 'break', a prefix is needed due to the loop's suffix.
xfix += Blockly.PHP.injectId(Blockly.PHP.STATEMENT_PREFIX, loop); xfix += PHP.injectId(PHP.STATEMENT_PREFIX, loop);
} }
} }
switch (block.getFieldValue('FLOW')) { switch (block.getFieldValue('FLOW')) {

View File

@@ -6,20 +6,19 @@
/** /**
* @fileoverview Generating PHP for math blocks. * @fileoverview Generating PHP for math blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.math'); goog.module('Blockly.PHP.math');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
const {NameType} = goog.require('Blockly.Names');
Blockly.PHP['math_number'] = function(block) { PHP['math_number'] = function(block) {
// Numeric value. // Numeric value.
let code = Number(block.getFieldValue('NUM')); let code = Number(block.getFieldValue('NUM'));
const order = code >= 0 ? Blockly.PHP.ORDER_ATOMIC : const order = code >= 0 ? PHP.ORDER_ATOMIC : PHP.ORDER_UNARY_NEGATION;
Blockly.PHP.ORDER_UNARY_NEGATION;
if (code === Infinity) { if (code === Infinity) {
code = 'INF'; code = 'INF';
} else if (code === -Infinity) { } else if (code === -Infinity) {
@@ -28,46 +27,43 @@ Blockly.PHP['math_number'] = function(block) {
return [code, order]; return [code, order];
}; };
Blockly.PHP['math_arithmetic'] = function(block) { PHP['math_arithmetic'] = function(block) {
// Basic arithmetic operators, and power. // Basic arithmetic operators, and power.
const OPERATORS = { const OPERATORS = {
'ADD': [' + ', Blockly.PHP.ORDER_ADDITION], 'ADD': [' + ', PHP.ORDER_ADDITION],
'MINUS': [' - ', Blockly.PHP.ORDER_SUBTRACTION], 'MINUS': [' - ', PHP.ORDER_SUBTRACTION],
'MULTIPLY': [' * ', Blockly.PHP.ORDER_MULTIPLICATION], 'MULTIPLY': [' * ', PHP.ORDER_MULTIPLICATION],
'DIVIDE': [' / ', Blockly.PHP.ORDER_DIVISION], 'DIVIDE': [' / ', PHP.ORDER_DIVISION],
'POWER': [' ** ', Blockly.PHP.ORDER_POWER] 'POWER': [' ** ', PHP.ORDER_POWER]
}; };
const tuple = OPERATORS[block.getFieldValue('OP')]; const tuple = OPERATORS[block.getFieldValue('OP')];
const operator = tuple[0]; const operator = tuple[0];
const order = tuple[1]; const order = tuple[1];
const argument0 = Blockly.PHP.valueToCode(block, 'A', order) || '0'; const argument0 = PHP.valueToCode(block, 'A', order) || '0';
const argument1 = Blockly.PHP.valueToCode(block, 'B', order) || '0'; const argument1 = PHP.valueToCode(block, 'B', order) || '0';
const code = argument0 + operator + argument1; const code = argument0 + operator + argument1;
return [code, order]; return [code, order];
}; };
Blockly.PHP['math_single'] = function(block) { PHP['math_single'] = function(block) {
// Math operators with single operand. // Math operators with single operand.
const operator = block.getFieldValue('OP'); const operator = block.getFieldValue('OP');
let code; let code;
let arg; let arg;
if (operator === 'NEG') { if (operator === 'NEG') {
// Negation is a special case given its different operator precedence. // Negation is a special case given its different operator precedence.
arg = Blockly.PHP.valueToCode(block, 'NUM', arg = PHP.valueToCode(block, 'NUM', PHP.ORDER_UNARY_NEGATION) || '0';
Blockly.PHP.ORDER_UNARY_NEGATION) || '0';
if (arg[0] === '-') { if (arg[0] === '-') {
// --3 is not legal in JS. // --3 is not legal in JS.
arg = ' ' + arg; arg = ' ' + arg;
} }
code = '-' + arg; code = '-' + arg;
return [code, Blockly.PHP.ORDER_UNARY_NEGATION]; return [code, PHP.ORDER_UNARY_NEGATION];
} }
if (operator === 'SIN' || operator === 'COS' || operator === 'TAN') { if (operator === 'SIN' || operator === 'COS' || operator === 'TAN') {
arg = Blockly.PHP.valueToCode(block, 'NUM', arg = PHP.valueToCode(block, 'NUM', PHP.ORDER_DIVISION) || '0';
Blockly.PHP.ORDER_DIVISION) || '0';
} else { } else {
arg = Blockly.PHP.valueToCode(block, 'NUM', arg = PHP.valueToCode(block, 'NUM', PHP.ORDER_NONE) || '0';
Blockly.PHP.ORDER_NONE) || '0';
} }
// First, handle cases which generate values that don't need parentheses // First, handle cases which generate values that don't need parentheses
// wrapping the code. // wrapping the code.
@@ -107,7 +103,7 @@ Blockly.PHP['math_single'] = function(block) {
break; break;
} }
if (code) { if (code) {
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
// Second, handle cases which generate values that may need parentheses // Second, handle cases which generate values that may need parentheses
// wrapping the code. // wrapping the code.
@@ -127,54 +123,47 @@ Blockly.PHP['math_single'] = function(block) {
default: default:
throw Error('Unknown math operator: ' + operator); throw Error('Unknown math operator: ' + operator);
} }
return [code, Blockly.PHP.ORDER_DIVISION]; return [code, PHP.ORDER_DIVISION];
}; };
Blockly.PHP['math_constant'] = function(block) { PHP['math_constant'] = function(block) {
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY. // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
const CONSTANTS = { const CONSTANTS = {
'PI': ['M_PI', Blockly.PHP.ORDER_ATOMIC], 'PI': ['M_PI', PHP.ORDER_ATOMIC],
'E': ['M_E', Blockly.PHP.ORDER_ATOMIC], 'E': ['M_E', PHP.ORDER_ATOMIC],
'GOLDEN_RATIO': ['(1 + sqrt(5)) / 2', Blockly.PHP.ORDER_DIVISION], 'GOLDEN_RATIO': ['(1 + sqrt(5)) / 2', PHP.ORDER_DIVISION],
'SQRT2': ['M_SQRT2', Blockly.PHP.ORDER_ATOMIC], 'SQRT2': ['M_SQRT2', PHP.ORDER_ATOMIC],
'SQRT1_2': ['M_SQRT1_2', Blockly.PHP.ORDER_ATOMIC], 'SQRT1_2': ['M_SQRT1_2', PHP.ORDER_ATOMIC],
'INFINITY': ['INF', Blockly.PHP.ORDER_ATOMIC] 'INFINITY': ['INF', PHP.ORDER_ATOMIC]
}; };
return CONSTANTS[block.getFieldValue('CONSTANT')]; return CONSTANTS[block.getFieldValue('CONSTANT')];
}; };
Blockly.PHP['math_number_property'] = function(block) { PHP['math_number_property'] = function(block) {
// Check if a number is even, odd, prime, whole, positive, or negative // Check if a number is even, odd, prime, whole, positive, or negative
// or if it is divisible by certain number. Returns true or false. // or if it is divisible by certain number. Returns true or false.
const number_to_check = Blockly.PHP.valueToCode(block, 'NUMBER_TO_CHECK', const number_to_check =
Blockly.PHP.ORDER_MODULUS) || '0'; PHP.valueToCode(block, 'NUMBER_TO_CHECK', PHP.ORDER_MODULUS) || '0';
const dropdown_property = block.getFieldValue('PROPERTY'); const dropdown_property = block.getFieldValue('PROPERTY');
let code; let code;
if (dropdown_property === 'PRIME') { if (dropdown_property === 'PRIME') {
// Prime is a special case as it is not a one-liner test. // Prime is a special case as it is not a one-liner test.
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('math_isPrime', [
'math_isPrime', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($n) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($n) {', ' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods', ' if ($n == 2 || $n == 3) {', ' return true;', ' }',
' if ($n == 2 || $n == 3) {', ' // False if n is NaN, negative, is 1, or not whole.',
' return true;', ' // And false if n is divisible by 2 or 3.',
' }', ' if (!is_numeric($n) || $n <= 1 || $n % 1 != 0 || $n % 2 == 0 ||' +
' // False if n is NaN, negative, is 1, or not whole.', ' $n % 3 == 0) {',
' // And false if n is divisible by 2 or 3.', ' return false;', ' }',
' if (!is_numeric($n) || $n <= 1 || $n % 1 != 0 || $n % 2 == 0 ||' + ' // Check all the numbers of form 6k +/- 1, up to sqrt(n).',
' $n % 3 == 0) {', ' for ($x = 6; $x <= sqrt($n) + 1; $x += 6) {',
' return false;', ' if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) {',
' }', ' return false;', ' }', ' }', ' return true;', '}'
' // Check all the numbers of form 6k +/- 1, up to sqrt(n).', ]);
' for ($x = 6; $x <= sqrt($n) + 1; $x += 6) {',
' if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) {',
' return false;',
' }',
' }',
' return true;',
'}']);
code = functionName + '(' + number_to_check + ')'; code = functionName + '(' + number_to_check + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
switch (dropdown_property) { switch (dropdown_property) {
case 'EVEN': case 'EVEN':
@@ -193,74 +182,68 @@ Blockly.PHP['math_number_property'] = function(block) {
code = number_to_check + ' < 0'; code = number_to_check + ' < 0';
break; break;
case 'DIVISIBLE_BY': { case 'DIVISIBLE_BY': {
const divisor = Blockly.PHP.valueToCode(block, 'DIVISOR', const divisor =
Blockly.PHP.ORDER_MODULUS) || '0'; PHP.valueToCode(block, 'DIVISOR', PHP.ORDER_MODULUS) || '0';
code = number_to_check + ' % ' + divisor + ' == 0'; code = number_to_check + ' % ' + divisor + ' == 0';
break; break;
} }
} }
return [code, Blockly.PHP.ORDER_EQUALITY]; return [code, PHP.ORDER_EQUALITY];
}; };
Blockly.PHP['math_change'] = function(block) { PHP['math_change'] = function(block) {
// Add to a variable in place. // Add to a variable in place.
const argument0 = Blockly.PHP.valueToCode(block, 'DELTA', const argument0 = PHP.valueToCode(block, 'DELTA', PHP.ORDER_ADDITION) || '0';
Blockly.PHP.ORDER_ADDITION) || '0'; const varName =
const varName = Blockly.PHP.nameDB_.getName( PHP.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME);
return varName + ' += ' + argument0 + ';\n'; return varName + ' += ' + argument0 + ';\n';
}; };
// Rounding functions have a single operand. // Rounding functions have a single operand.
Blockly.PHP['math_round'] = Blockly.PHP['math_single']; PHP['math_round'] = PHP['math_single'];
// Trigonometry functions have a single operand. // Trigonometry functions have a single operand.
Blockly.PHP['math_trig'] = Blockly.PHP['math_single']; PHP['math_trig'] = PHP['math_single'];
Blockly.PHP['math_on_list'] = function(block) { PHP['math_on_list'] = function(block) {
// Math functions for lists. // Math functions for lists.
const func = block.getFieldValue('OP'); const func = block.getFieldValue('OP');
let list; let list;
let code; let code;
switch (func) { switch (func) {
case 'SUM': case 'SUM':
list = Blockly.PHP.valueToCode(block, 'LIST', list =
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()'; PHP.valueToCode(block, 'LIST', PHP.ORDER_FUNCTION_CALL) || 'array()';
code = 'array_sum(' + list + ')'; code = 'array_sum(' + list + ')';
break; break;
case 'MIN': case 'MIN':
list = Blockly.PHP.valueToCode(block, 'LIST', list =
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()'; PHP.valueToCode(block, 'LIST', PHP.ORDER_FUNCTION_CALL) || 'array()';
code = 'min(' + list + ')'; code = 'min(' + list + ')';
break; break;
case 'MAX': case 'MAX':
list = Blockly.PHP.valueToCode(block, 'LIST', list =
Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()'; PHP.valueToCode(block, 'LIST', PHP.ORDER_FUNCTION_CALL) || 'array()';
code = 'max(' + list + ')'; code = 'max(' + list + ')';
break; break;
case 'AVERAGE': { case 'AVERAGE': {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('math_mean', [
'math_mean', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($myList) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' return array_sum($myList) / count($myList);', '}'
'($myList) {', ]);
' return array_sum($myList) / count($myList);', list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || 'array()';
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || 'array()';
code = functionName + '(' + list + ')'; code = functionName + '(' + list + ')';
break; break;
} }
case 'MEDIAN': { case 'MEDIAN': {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('math_median', [
'math_median', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($arr) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' sort($arr,SORT_NUMERIC);',
'($arr) {', ' return (count($arr) % 2) ? $arr[floor(count($arr)/2)] : ',
' sort($arr,SORT_NUMERIC);', ' ($arr[floor(count($arr)/2)] + $arr[floor(count($arr)/2)' +
' return (count($arr) % 2) ? $arr[floor(count($arr)/2)] : ', ' - 1]) / 2;',
' ($arr[floor(count($arr)/2)] + $arr[floor(count($arr)/2)' + '}'
' - 1]) / 2;', ]);
'}']); list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]';
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')'; code = functionName + '(' + list + ')';
break; break;
} }
@@ -268,110 +251,90 @@ Blockly.PHP['math_on_list'] = function(block) {
// As a list of numbers can contain more than one mode, // As a list of numbers can contain more than one mode,
// the returned result is provided as an array. // the returned result is provided as an array.
// Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1]. // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('math_modes', [
'math_modes', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($values) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' if (empty($values)) return array();',
'($values) {', ' $counts = array_count_values($values);',
' if (empty($values)) return array();', ' arsort($counts); // Sort counts in descending order',
' $counts = array_count_values($values);', ' $modes = array_keys($counts, current($counts), true);',
' arsort($counts); // Sort counts in descending order', ' return $modes;', '}'
' $modes = array_keys($counts, current($counts), true);', ]);
' return $modes;', list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]';
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')'; code = functionName + '(' + list + ')';
break; break;
} }
case 'STD_DEV': { case 'STD_DEV': {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('math_standard_deviation', [
'math_standard_deviation', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($numbers) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' $n = count($numbers);', ' if (!$n) return null;',
'($numbers) {', ' $mean = array_sum($numbers) / count($numbers);',
' $n = count($numbers);', ' foreach($numbers as $key => $num) $devs[$key] = ' +
' if (!$n) return null;', 'pow($num - $mean, 2);',
' $mean = array_sum($numbers) / count($numbers);', ' return sqrt(array_sum($devs) / (count($devs) - 1));', '}'
' foreach($numbers as $key => $num) $devs[$key] = ' + ]);
'pow($num - $mean, 2);', list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]';
' return sqrt(array_sum($devs) / (count($devs) - 1));',
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')'; code = functionName + '(' + list + ')';
break; break;
} }
case 'RANDOM': { case 'RANDOM': {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('math_random_list', [
'math_random_list', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($list) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ' $x = rand(0, count($list)-1);', ' return $list[$x];', '}'
'($list) {', ]);
' $x = rand(0, count($list)-1);', list = PHP.valueToCode(block, 'LIST', PHP.ORDER_NONE) || '[]';
' return $list[$x];',
'}']);
list = Blockly.PHP.valueToCode(block, 'LIST',
Blockly.PHP.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')'; code = functionName + '(' + list + ')';
break; break;
} }
default: default:
throw Error('Unknown operator: ' + func); throw Error('Unknown operator: ' + func);
} }
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['math_modulo'] = function(block) { PHP['math_modulo'] = function(block) {
// Remainder computation. // Remainder computation.
const argument0 = Blockly.PHP.valueToCode(block, 'DIVIDEND', const argument0 =
Blockly.PHP.ORDER_MODULUS) || '0'; PHP.valueToCode(block, 'DIVIDEND', PHP.ORDER_MODULUS) || '0';
const argument1 = Blockly.PHP.valueToCode(block, 'DIVISOR', const argument1 = PHP.valueToCode(block, 'DIVISOR', PHP.ORDER_MODULUS) || '0';
Blockly.PHP.ORDER_MODULUS) || '0';
const code = argument0 + ' % ' + argument1; const code = argument0 + ' % ' + argument1;
return [code, Blockly.PHP.ORDER_MODULUS]; return [code, PHP.ORDER_MODULUS];
}; };
Blockly.PHP['math_constrain'] = function(block) { PHP['math_constrain'] = function(block) {
// Constrain a number between two limits. // Constrain a number between two limits.
const argument0 = Blockly.PHP.valueToCode(block, 'VALUE', const argument0 = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '0';
Blockly.PHP.ORDER_NONE) || '0'; const argument1 = PHP.valueToCode(block, 'LOW', PHP.ORDER_NONE) || '0';
const argument1 = Blockly.PHP.valueToCode(block, 'LOW', const argument2 =
Blockly.PHP.ORDER_NONE) || '0'; PHP.valueToCode(block, 'HIGH', PHP.ORDER_NONE) || 'Infinity';
const argument2 = Blockly.PHP.valueToCode(block, 'HIGH', const code =
Blockly.PHP.ORDER_NONE) || 'Infinity'; 'min(max(' + argument0 + ', ' + argument1 + '), ' + argument2 + ')';
const code = 'min(max(' + argument0 + ', ' + argument1 + '), ' + return [code, PHP.ORDER_FUNCTION_CALL];
argument2 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['math_random_int'] = function(block) { PHP['math_random_int'] = function(block) {
// Random integer between [X] and [Y]. // Random integer between [X] and [Y].
const argument0 = Blockly.PHP.valueToCode(block, 'FROM', const argument0 = PHP.valueToCode(block, 'FROM', PHP.ORDER_NONE) || '0';
Blockly.PHP.ORDER_NONE) || '0'; const argument1 = PHP.valueToCode(block, 'TO', PHP.ORDER_NONE) || '0';
const argument1 = Blockly.PHP.valueToCode(block, 'TO', const functionName = PHP.provideFunction_('math_random_int', [
Blockly.PHP.ORDER_NONE) || '0'; 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($a, $b) {',
const functionName = Blockly.PHP.provideFunction_( ' if ($a > $b) {', ' return rand($b, $a);', ' }',
'math_random_int', ' return rand($a, $b);', '}'
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + ]);
'($a, $b) {',
' if ($a > $b) {',
' return rand($b, $a);',
' }',
' return rand($a, $b);',
'}']);
const code = functionName + '(' + argument0 + ', ' + argument1 + ')'; const code = functionName + '(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['math_random_float'] = function(block) { PHP['math_random_float'] = function(block) {
// Random fraction between 0 and 1. // Random fraction between 0 and 1.
return ['(float)rand()/(float)getrandmax()', Blockly.PHP.ORDER_FUNCTION_CALL]; return ['(float)rand()/(float)getrandmax()', PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['math_atan2'] = function(block) { PHP['math_atan2'] = function(block) {
// Arctangent of point (X, Y) in degrees from -180 to 180. // Arctangent of point (X, Y) in degrees from -180 to 180.
const argument0 = Blockly.PHP.valueToCode(block, 'X', const argument0 = PHP.valueToCode(block, 'X', PHP.ORDER_NONE) || '0';
Blockly.PHP.ORDER_NONE) || '0'; const argument1 = PHP.valueToCode(block, 'Y', PHP.ORDER_NONE) || '0';
const argument1 = Blockly.PHP.valueToCode(block, 'Y', return [
Blockly.PHP.ORDER_NONE) || '0'; 'atan2(' + argument1 + ', ' + argument0 + ') / pi() * 180',
return ['atan2(' + argument1 + ', ' + argument0 + ') / pi() * 180', PHP.ORDER_DIVISION
Blockly.PHP.ORDER_DIVISION]; ];
}; };

View File

@@ -6,128 +6,119 @@
/** /**
* @fileoverview Generating PHP for procedure blocks. * @fileoverview Generating PHP for procedure blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.procedures'); goog.module('Blockly.PHP.procedures');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
goog.require('Blockly.Names'); const Variables = goog.require('Blockly.Variables');
goog.require('Blockly.Variables'); const {NameType} = goog.require('Blockly.Names');
Blockly.PHP['procedures_defreturn'] = function(block) { PHP['procedures_defreturn'] = function(block) {
// Define a procedure with a return value. // Define a procedure with a return value.
// First, add a 'global' statement for every variable that is not shadowed by // First, add a 'global' statement for every variable that is not shadowed by
// a local parameter. // a local parameter.
const globals = []; const globals = [];
const workspace = block.workspace; const workspace = block.workspace;
const usedVariables = Blockly.Variables.allUsedVarModels(workspace) || []; const usedVariables = Variables.allUsedVarModels(workspace) || [];
for (let i = 0, variable; variable = usedVariables[i]; i++) { for (let i = 0, variable; variable = usedVariables[i]; i++) {
const varName = variable.name; const varName = variable.name;
if (block.getVars().indexOf(varName) === -1) { if (block.getVars().indexOf(varName) === -1) {
globals.push(Blockly.PHP.nameDB_.getName(varName, globals.push(PHP.nameDB_.getName(varName, NameType.VARIABLE));
Blockly.VARIABLE_CATEGORY_NAME));
} }
} }
// Add developer variables. // Add developer variables.
const devVarList = Blockly.Variables.allDeveloperVariables(workspace); const devVarList = Variables.allDeveloperVariables(workspace);
for (let i = 0; i < devVarList.length; i++) { for (let i = 0; i < devVarList.length; i++) {
globals.push(Blockly.PHP.nameDB_.getName(devVarList[i], globals.push(
Blockly.Names.DEVELOPER_VARIABLE_TYPE)); PHP.nameDB_.getName(devVarList[i], NameType.DEVELOPER_VARIABLE));
} }
const globalStr = globals.length ? const globalStr =
Blockly.PHP.INDENT + 'global ' + globals.join(', ') + ';\n' : ''; globals.length ? PHP.INDENT + 'global ' + globals.join(', ') + ';\n' : '';
const funcName = Blockly.PHP.nameDB_.getName( const funcName =
block.getFieldValue('NAME'), Blockly.PROCEDURE_CATEGORY_NAME); PHP.nameDB_.getName(block.getFieldValue('NAME'), NameType.PROCEDURE);
let xfix1 = ''; let xfix1 = '';
if (Blockly.PHP.STATEMENT_PREFIX) { if (PHP.STATEMENT_PREFIX) {
xfix1 += Blockly.PHP.injectId(Blockly.PHP.STATEMENT_PREFIX, block); xfix1 += PHP.injectId(PHP.STATEMENT_PREFIX, block);
} }
if (Blockly.PHP.STATEMENT_SUFFIX) { if (PHP.STATEMENT_SUFFIX) {
xfix1 += Blockly.PHP.injectId(Blockly.PHP.STATEMENT_SUFFIX, block); xfix1 += PHP.injectId(PHP.STATEMENT_SUFFIX, block);
} }
if (xfix1) { if (xfix1) {
xfix1 = Blockly.PHP.prefixLines(xfix1, Blockly.PHP.INDENT); xfix1 = PHP.prefixLines(xfix1, PHP.INDENT);
} }
let loopTrap = ''; let loopTrap = '';
if (Blockly.PHP.INFINITE_LOOP_TRAP) { if (PHP.INFINITE_LOOP_TRAP) {
loopTrap = Blockly.PHP.prefixLines( loopTrap = PHP.prefixLines(
Blockly.PHP.injectId(Blockly.PHP.INFINITE_LOOP_TRAP, block), PHP.injectId(PHP.INFINITE_LOOP_TRAP, block), PHP.INDENT);
Blockly.PHP.INDENT);
} }
const branch = Blockly.PHP.statementToCode(block, 'STACK'); const branch = PHP.statementToCode(block, 'STACK');
let returnValue = Blockly.PHP.valueToCode(block, 'RETURN', let returnValue = PHP.valueToCode(block, 'RETURN', PHP.ORDER_NONE) || '';
Blockly.PHP.ORDER_NONE) || '';
let xfix2 = ''; let xfix2 = '';
if (branch && returnValue) { if (branch && returnValue) {
// After executing the function body, revisit this block for the return. // After executing the function body, revisit this block for the return.
xfix2 = xfix1; xfix2 = xfix1;
} }
if (returnValue) { if (returnValue) {
returnValue = Blockly.PHP.INDENT + 'return ' + returnValue + ';\n'; returnValue = PHP.INDENT + 'return ' + returnValue + ';\n';
} }
const args = []; const args = [];
const variables = block.getVars(); const variables = block.getVars();
for (let i = 0; i < variables.length; i++) { for (let i = 0; i < variables.length; i++) {
args[i] = Blockly.PHP.nameDB_.getName(variables[i], args[i] = PHP.nameDB_.getName(variables[i], NameType.VARIABLE);
Blockly.VARIABLE_CATEGORY_NAME);
} }
let code = 'function ' + funcName + '(' + args.join(', ') + ') {\n' + let code = 'function ' + funcName + '(' + args.join(', ') + ') {\n' +
globalStr + xfix1 + loopTrap + branch + xfix2 + returnValue + '}'; globalStr + xfix1 + loopTrap + branch + xfix2 + returnValue + '}';
code = Blockly.PHP.scrub_(block, code); code = PHP.scrub_(block, code);
// Add % so as not to collide with helper functions in definitions list. // Add % so as not to collide with helper functions in definitions list.
Blockly.PHP.definitions_['%' + funcName] = code; PHP.definitions_['%' + funcName] = code;
return null; return null;
}; };
// Defining a procedure without a return value uses the same generator as // Defining a procedure without a return value uses the same generator as
// a procedure with a return value. // a procedure with a return value.
Blockly.PHP['procedures_defnoreturn'] = PHP['procedures_defnoreturn'] = PHP['procedures_defreturn'];
Blockly.PHP['procedures_defreturn'];
Blockly.PHP['procedures_callreturn'] = function(block) { PHP['procedures_callreturn'] = function(block) {
// Call a procedure with a return value. // Call a procedure with a return value.
const funcName = Blockly.PHP.nameDB_.getName( const funcName =
block.getFieldValue('NAME'), Blockly.PROCEDURE_CATEGORY_NAME); PHP.nameDB_.getName(block.getFieldValue('NAME'), NameType.PROCEDURE);
const args = []; const args = [];
const variables = block.getVars(); const variables = block.getVars();
for (let i = 0; i < variables.length; i++) { for (let i = 0; i < variables.length; i++) {
args[i] = Blockly.PHP.valueToCode(block, 'ARG' + i, args[i] = PHP.valueToCode(block, 'ARG' + i, PHP.ORDER_NONE) || 'null';
Blockly.PHP.ORDER_NONE) || 'null';
} }
const code = funcName + '(' + args.join(', ') + ')'; const code = funcName + '(' + args.join(', ') + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['procedures_callnoreturn'] = function(block) { PHP['procedures_callnoreturn'] = function(block) {
// Call a procedure with no return value. // Call a procedure with no return value.
// Generated code is for a function call as a statement is the same as a // Generated code is for a function call as a statement is the same as a
// function call as a value, with the addition of line ending. // function call as a value, with the addition of line ending.
const tuple = Blockly.PHP['procedures_callreturn'](block); const tuple = PHP['procedures_callreturn'](block);
return tuple[0] + ';\n'; return tuple[0] + ';\n';
}; };
Blockly.PHP['procedures_ifreturn'] = function(block) { PHP['procedures_ifreturn'] = function(block) {
// Conditionally return value from a procedure. // Conditionally return value from a procedure.
const condition = Blockly.PHP.valueToCode(block, 'CONDITION', const condition =
Blockly.PHP.ORDER_NONE) || 'false'; PHP.valueToCode(block, 'CONDITION', PHP.ORDER_NONE) || 'false';
let code = 'if (' + condition + ') {\n'; let code = 'if (' + condition + ') {\n';
if (Blockly.PHP.STATEMENT_SUFFIX) { if (PHP.STATEMENT_SUFFIX) {
// Inject any statement suffix here since the regular one at the end // Inject any statement suffix here since the regular one at the end
// will not get executed if the return is triggered. // will not get executed if the return is triggered.
code += Blockly.PHP.prefixLines( code +=
Blockly.PHP.injectId(Blockly.PHP.STATEMENT_SUFFIX, block), PHP.prefixLines(PHP.injectId(PHP.STATEMENT_SUFFIX, block), PHP.INDENT);
Blockly.PHP.INDENT);
} }
if (block.hasReturnValue_) { if (block.hasReturnValue_) {
const value = Blockly.PHP.valueToCode(block, 'VALUE', const value = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || 'null';
Blockly.PHP.ORDER_NONE) || 'null'; code += PHP.INDENT + 'return ' + value + ';\n';
code += Blockly.PHP.INDENT + 'return ' + value + ';\n';
} else { } else {
code += Blockly.PHP.INDENT + 'return;\n'; code += PHP.INDENT + 'return;\n';
} }
code += '}\n'; code += '}\n';
return code; return code;

View File

@@ -6,198 +6,184 @@
/** /**
* @fileoverview Generating PHP for text blocks. * @fileoverview Generating PHP for text blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.texts'); goog.module('Blockly.PHP.texts');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
const {NameType} = goog.require('Blockly.Names');
Blockly.PHP['text'] = function(block) { PHP['text'] = function(block) {
// Text value. // Text value.
const code = Blockly.PHP.quote_(block.getFieldValue('TEXT')); const code = PHP.quote_(block.getFieldValue('TEXT'));
return [code, Blockly.PHP.ORDER_ATOMIC]; return [code, PHP.ORDER_ATOMIC];
}; };
Blockly.PHP['text_multiline'] = function(block) { PHP['text_multiline'] = function(block) {
// Text value. // Text value.
const code = Blockly.PHP.multiline_quote_(block.getFieldValue('TEXT')); const code = PHP.multiline_quote_(block.getFieldValue('TEXT'));
const order = code.indexOf('.') !== -1 ? Blockly.PHP.ORDER_STRING_CONCAT : const order =
Blockly.PHP.ORDER_ATOMIC; code.indexOf('.') !== -1 ? PHP.ORDER_STRING_CONCAT : PHP.ORDER_ATOMIC;
return [code, order]; return [code, order];
}; };
Blockly.PHP['text_join'] = function(block) { PHP['text_join'] = function(block) {
// Create a string made up of any number of elements of any type. // Create a string made up of any number of elements of any type.
if (block.itemCount_ === 0) { if (block.itemCount_ === 0) {
return ['\'\'', Blockly.PHP.ORDER_ATOMIC]; return ['\'\'', PHP.ORDER_ATOMIC];
} else if (block.itemCount_ === 1) { } else if (block.itemCount_ === 1) {
const element = Blockly.PHP.valueToCode(block, 'ADD0', const element = PHP.valueToCode(block, 'ADD0', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\'';
const code = element; const code = element;
return [code, Blockly.PHP.ORDER_NONE]; return [code, PHP.ORDER_NONE];
} else if (block.itemCount_ === 2) { } else if (block.itemCount_ === 2) {
const element0 = Blockly.PHP.valueToCode(block, 'ADD0', const element0 =
Blockly.PHP.ORDER_STRING_CONCAT) || '\'\''; PHP.valueToCode(block, 'ADD0', PHP.ORDER_STRING_CONCAT) || '\'\'';
const element1 = Blockly.PHP.valueToCode(block, 'ADD1', const element1 =
Blockly.PHP.ORDER_STRING_CONCAT) || '\'\''; PHP.valueToCode(block, 'ADD1', PHP.ORDER_STRING_CONCAT) || '\'\'';
const code = element0 + ' . ' + element1; const code = element0 + ' . ' + element1;
return [code, Blockly.PHP.ORDER_STRING_CONCAT]; return [code, PHP.ORDER_STRING_CONCAT];
} else { } else {
const elements = new Array(block.itemCount_); const elements = new Array(block.itemCount_);
for (let i = 0; i < block.itemCount_; i++) { for (let i = 0; i < block.itemCount_; i++) {
elements[i] = Blockly.PHP.valueToCode(block, 'ADD' + i, elements[i] = PHP.valueToCode(block, 'ADD' + i, PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\'';
} }
const code = 'implode(\'\', array(' + elements.join(',') + '))'; const code = 'implode(\'\', array(' + elements.join(',') + '))';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
}; };
Blockly.PHP['text_append'] = function(block) { PHP['text_append'] = function(block) {
// Append to a variable in place. // Append to a variable in place.
const varName = Blockly.PHP.nameDB_.getName( const varName =
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME); PHP.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
const value = Blockly.PHP.valueToCode(block, 'TEXT', const value = PHP.valueToCode(block, 'TEXT', PHP.ORDER_ASSIGNMENT) || '\'\'';
Blockly.PHP.ORDER_ASSIGNMENT) || '\'\'';
return varName + ' .= ' + value + ';\n'; return varName + ' .= ' + value + ';\n';
}; };
Blockly.PHP['text_length'] = function(block) { PHP['text_length'] = function(block) {
// String or array length. // String or array length.
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('length', [
'length', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($value) {', ' if (is_string($value)) {', ' return strlen($value);', ' } else {',
' if (is_string($value)) {', ' return count($value);', ' }', '}'
' return strlen($value);', ]);
' } else {', const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '\'\'';
' return count($value);', return [functionName + '(' + text + ')', PHP.ORDER_FUNCTION_CALL];
' }',
'}']);
const text = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_NONE) || '\'\'';
return [functionName + '(' + text + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['text_isEmpty'] = function(block) { PHP['text_isEmpty'] = function(block) {
// Is the string null or array empty? // Is the string null or array empty?
const text = Blockly.PHP.valueToCode(block, 'VALUE', const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\''; return ['empty(' + text + ')', PHP.ORDER_FUNCTION_CALL];
return ['empty(' + text + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['text_indexOf'] = function(block) { PHP['text_indexOf'] = function(block) {
// Search the text for a substring. // Search the text for a substring.
const operator = block.getFieldValue('END') === 'FIRST' ? const operator =
'strpos' : 'strrpos'; block.getFieldValue('END') === 'FIRST' ? 'strpos' : 'strrpos';
const substring = Blockly.PHP.valueToCode(block, 'FIND', const substring = PHP.valueToCode(block, 'FIND', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\''; const text = PHP.valueToCode(block, 'VALUE', PHP.ORDER_NONE) || '\'\'';
const text = Blockly.PHP.valueToCode(block, 'VALUE',
Blockly.PHP.ORDER_NONE) || '\'\'';
let errorIndex = ' -1'; let errorIndex = ' -1';
let indexAdjustment = ''; let indexAdjustment = '';
if (block.workspace.options.oneBasedIndex) { if (block.workspace.options.oneBasedIndex) {
errorIndex = ' 0'; errorIndex = ' 0';
indexAdjustment = ' + 1'; indexAdjustment = ' + 1';
} }
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_(
block.getFieldValue('END') === 'FIRST' ? block.getFieldValue('END') === 'FIRST' ? 'text_indexOf' :
'text_indexOf' : 'text_lastIndexOf', 'text_lastIndexOf',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + [
'($text, $search) {', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($text, $search) {',
' $pos = ' + operator + '($text, $search);', ' $pos = ' + operator + '($text, $search);',
' return $pos === false ? ' + errorIndex + ' : $pos' + ' return $pos === false ? ' + errorIndex + ' : $pos' +
indexAdjustment + ';', indexAdjustment + ';',
'}']); '}'
]);
const code = functionName + '(' + text + ', ' + substring + ')'; const code = functionName + '(' + text + ', ' + substring + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['text_charAt'] = function(block) { PHP['text_charAt'] = function(block) {
// Get letter at index. // Get letter at index.
const where = block.getFieldValue('WHERE') || 'FROM_START'; const where = block.getFieldValue('WHERE') || 'FROM_START';
const textOrder = (where === 'RANDOM') ? Blockly.PHP.ORDER_NONE : const textOrder = (where === 'RANDOM') ? PHP.ORDER_NONE : PHP.ORDER_NONE;
Blockly.PHP.ORDER_NONE; const text = PHP.valueToCode(block, 'VALUE', textOrder) || '\'\'';
const text = Blockly.PHP.valueToCode(block, 'VALUE', textOrder) || '\'\'';
switch (where) { switch (where) {
case 'FIRST': { case 'FIRST': {
const code = 'substr(' + text + ', 0, 1)'; const code = 'substr(' + text + ', 0, 1)';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
case 'LAST': { case 'LAST': {
const code = 'substr(' + text + ', -1)'; const code = 'substr(' + text + ', -1)';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
case 'FROM_START': { case 'FROM_START': {
const at = Blockly.PHP.getAdjusted(block, 'AT'); const at = PHP.getAdjusted(block, 'AT');
const code = 'substr(' + text + ', ' + at + ', 1)'; const code = 'substr(' + text + ', ' + at + ', 1)';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
case 'FROM_END': { case 'FROM_END': {
const at = Blockly.PHP.getAdjusted(block, 'AT', 1, true); const at = PHP.getAdjusted(block, 'AT', 1, true);
const code = 'substr(' + text + ', ' + at + ', 1)'; const code = 'substr(' + text + ', ' + at + ', 1)';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
case 'RANDOM': { case 'RANDOM': {
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('text_random_letter', [
'text_random_letter', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ + '($text) {',
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($text) {', ' return $text[rand(0, strlen($text) - 1)];', '}'
' return $text[rand(0, strlen($text) - 1)];', ]);
'}']);
const code = functionName + '(' + text + ')'; const code = functionName + '(' + text + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
} }
throw Error('Unhandled option (text_charAt).'); throw Error('Unhandled option (text_charAt).');
}; };
Blockly.PHP['text_getSubstring'] = function(block) { PHP['text_getSubstring'] = function(block) {
// Get substring. // Get substring.
const where1 = block.getFieldValue('WHERE1'); const where1 = block.getFieldValue('WHERE1');
const where2 = block.getFieldValue('WHERE2'); const where2 = block.getFieldValue('WHERE2');
const text = Blockly.PHP.valueToCode(block, 'STRING', const text = PHP.valueToCode(block, 'STRING', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\'';
if (where1 === 'FIRST' && where2 === 'LAST') { if (where1 === 'FIRST' && where2 === 'LAST') {
const code = text; const code = text;
return [code, Blockly.PHP.ORDER_NONE]; return [code, PHP.ORDER_NONE];
} else { } else {
const at1 = Blockly.PHP.getAdjusted(block, 'AT1'); const at1 = PHP.getAdjusted(block, 'AT1');
const at2 = Blockly.PHP.getAdjusted(block, 'AT2'); const at2 = PHP.getAdjusted(block, 'AT2');
const functionName = Blockly.PHP.provideFunction_( const functionName = PHP.provideFunction_('text_get_substring', [
'text_get_substring', 'function ' + PHP.FUNCTION_NAME_PLACEHOLDER_ +
['function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($text, $where1, $at1, $where2, $at2) {',
'($text, $where1, $at1, $where2, $at2) {', ' if ($where1 == \'FROM_END\') {',
' if ($where1 == \'FROM_END\') {', ' $at1 = strlen($text) - 1 - $at1;',
' $at1 = strlen($text) - 1 - $at1;', ' } else if ($where1 == \'FIRST\') {',
' } else if ($where1 == \'FIRST\') {', ' $at1 = 0;',
' $at1 = 0;', ' } else if ($where1 != \'FROM_START\') {',
' } else if ($where1 != \'FROM_START\') {', ' throw new Exception(\'Unhandled option (text_get_substring).\');',
' throw new Exception(\'Unhandled option (text_get_substring).\');', ' }',
' }', ' $length = 0;',
' $length = 0;', ' if ($where2 == \'FROM_START\') {',
' if ($where2 == \'FROM_START\') {', ' $length = $at2 - $at1 + 1;',
' $length = $at2 - $at1 + 1;', ' } else if ($where2 == \'FROM_END\') {',
' } else if ($where2 == \'FROM_END\') {', ' $length = strlen($text) - $at1 - $at2;',
' $length = strlen($text) - $at1 - $at2;', ' } else if ($where2 == \'LAST\') {',
' } else if ($where2 == \'LAST\') {', ' $length = strlen($text) - $at1;',
' $length = strlen($text) - $at1;', ' } else {',
' } else {', ' throw new Exception(\'Unhandled option (text_get_substring).\');',
' throw new Exception(\'Unhandled option (text_get_substring).\');', ' }',
' }', ' return substr($text, $at1, $length);',
' return substr($text, $at1, $length);', '}'
'}']); ]);
const code = functionName + '(' + text + ', \'' + const code = functionName + '(' + text + ', \'' + where1 + '\', ' + at1 +
where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')'; ', \'' + where2 + '\', ' + at2 + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
} }
}; };
Blockly.PHP['text_changeCase'] = function(block) { PHP['text_changeCase'] = function(block) {
// Change capitalization. // Change capitalization.
const text = Blockly.PHP.valueToCode(block, 'TEXT', const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\'';
let code; let code;
if (block.getFieldValue('CASE') === 'UPPERCASE') { if (block.getFieldValue('CASE') === 'UPPERCASE') {
code = 'strtoupper(' + text + ')'; code = 'strtoupper(' + text + ')';
@@ -206,75 +192,62 @@ Blockly.PHP['text_changeCase'] = function(block) {
} else if (block.getFieldValue('CASE') === 'TITLECASE') { } else if (block.getFieldValue('CASE') === 'TITLECASE') {
code = 'ucwords(strtolower(' + text + '))'; code = 'ucwords(strtolower(' + text + '))';
} }
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['text_trim'] = function(block) { PHP['text_trim'] = function(block) {
// Trim spaces. // Trim spaces.
const OPERATORS = { const OPERATORS = {'LEFT': 'ltrim', 'RIGHT': 'rtrim', 'BOTH': 'trim'};
'LEFT': 'ltrim',
'RIGHT': 'rtrim',
'BOTH': 'trim'
};
const operator = OPERATORS[block.getFieldValue('MODE')]; const operator = OPERATORS[block.getFieldValue('MODE')];
const text = Blockly.PHP.valueToCode(block, 'TEXT', const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\''; return [operator + '(' + text + ')', PHP.ORDER_FUNCTION_CALL];
return [operator + '(' + text + ')', Blockly.PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['text_print'] = function(block) { PHP['text_print'] = function(block) {
// Print statement. // Print statement.
const msg = Blockly.PHP.valueToCode(block, 'TEXT', const msg = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\'';
return 'print(' + msg + ');\n'; return 'print(' + msg + ');\n';
}; };
Blockly.PHP['text_prompt_ext'] = function(block) { PHP['text_prompt_ext'] = function(block) {
// Prompt function. // Prompt function.
let msg; let msg;
if (block.getField('TEXT')) { if (block.getField('TEXT')) {
// Internal message. // Internal message.
msg = Blockly.PHP.quote_(block.getFieldValue('TEXT')); msg = PHP.quote_(block.getFieldValue('TEXT'));
} else { } else {
// External message. // External message.
msg = Blockly.PHP.valueToCode(block, 'TEXT', msg = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\'';
} }
let code = 'readline(' + msg + ')'; let code = 'readline(' + msg + ')';
const toNumber = block.getFieldValue('TYPE') === 'NUMBER'; const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
if (toNumber) { if (toNumber) {
code = 'floatval(' + code + ')'; code = 'floatval(' + code + ')';
} }
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['text_prompt'] = Blockly.PHP['text_prompt_ext']; PHP['text_prompt'] = PHP['text_prompt_ext'];
Blockly.PHP['text_count'] = function(block) { PHP['text_count'] = function(block) {
const text = Blockly.PHP.valueToCode(block, 'TEXT', const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\''; const sub = PHP.valueToCode(block, 'SUB', PHP.ORDER_NONE) || '\'\'';
const sub = Blockly.PHP.valueToCode(block, 'SUB', const code = 'strlen(' + sub + ') === 0' +
Blockly.PHP.ORDER_NONE) || '\'\''; ' ? strlen(' + text + ') + 1' +
const code = 'strlen(' + sub + ') === 0' ' : substr_count(' + text + ', ' + sub + ')';
+ ' ? strlen(' + text + ') + 1' return [code, PHP.ORDER_CONDITIONAL];
+ ' : substr_count(' + text + ', ' + sub + ')';
return [code, Blockly.PHP.ORDER_CONDITIONAL];
}; };
Blockly.PHP['text_replace'] = function(block) { PHP['text_replace'] = function(block) {
const text = Blockly.PHP.valueToCode(block, 'TEXT', const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\''; const from = PHP.valueToCode(block, 'FROM', PHP.ORDER_NONE) || '\'\'';
const from = Blockly.PHP.valueToCode(block, 'FROM', const to = PHP.valueToCode(block, 'TO', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\'';
const to = Blockly.PHP.valueToCode(block, 'TO',
Blockly.PHP.ORDER_NONE) || '\'\'';
const code = 'str_replace(' + from + ', ' + to + ', ' + text + ')'; const code = 'str_replace(' + from + ', ' + to + ', ' + text + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };
Blockly.PHP['text_reverse'] = function(block) { PHP['text_reverse'] = function(block) {
const text = Blockly.PHP.valueToCode(block, 'TEXT', const text = PHP.valueToCode(block, 'TEXT', PHP.ORDER_NONE) || '\'\'';
Blockly.PHP.ORDER_NONE) || '\'\'';
const code = 'strrev(' + text + ')'; const code = 'strrev(' + text + ')';
return [code, Blockly.PHP.ORDER_FUNCTION_CALL]; return [code, PHP.ORDER_FUNCTION_CALL];
}; };

View File

@@ -6,27 +6,27 @@
/** /**
* @fileoverview Generating PHP for variable blocks. * @fileoverview Generating PHP for variable blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.variables'); goog.module('Blockly.PHP.variables');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
const {NameType} = goog.require('Blockly.Names');
Blockly.PHP['variables_get'] = function(block) { PHP['variables_get'] = function(block) {
// Variable getter. // Variable getter.
const code = Blockly.PHP.nameDB_.getName(block.getFieldValue('VAR'), const code =
Blockly.VARIABLE_CATEGORY_NAME); PHP.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
return [code, Blockly.PHP.ORDER_ATOMIC]; return [code, PHP.ORDER_ATOMIC];
}; };
Blockly.PHP['variables_set'] = function(block) { PHP['variables_set'] = function(block) {
// Variable setter. // Variable setter.
const argument0 = Blockly.PHP.valueToCode(block, 'VALUE', const argument0 =
Blockly.PHP.ORDER_ASSIGNMENT) || '0'; PHP.valueToCode(block, 'VALUE', PHP.ORDER_ASSIGNMENT) || '0';
const varName = Blockly.PHP.nameDB_.getName( const varName =
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME); PHP.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
return varName + ' = ' + argument0 + ';\n'; return varName + ' = ' + argument0 + ';\n';
}; };

View File

@@ -6,16 +6,16 @@
/** /**
* @fileoverview Generating PHP for dynamic variable blocks. * @fileoverview Generating PHP for dynamic variable blocks.
* @suppress {extraRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.PHP.variablesDynamic'); goog.module('Blockly.PHP.variablesDynamic');
goog.require('Blockly.PHP'); const PHP = goog.require('Blockly.PHP');
/** @suppress {extraRequire} */
goog.require('Blockly.PHP.variables'); goog.require('Blockly.PHP.variables');
// PHP is dynamically typed. // PHP is dynamically typed.
Blockly.PHP['variables_get_dynamic'] = Blockly.PHP['variables_get']; PHP['variables_get_dynamic'] = PHP['variables_get'];
Blockly.PHP['variables_set_dynamic'] = Blockly.PHP['variables_set']; PHP['variables_set_dynamic'] = PHP['variables_set'];

View File

@@ -287,7 +287,7 @@ goog.addDependency('../../generators/javascript/procedures.js', ['Blockly.JavaSc
goog.addDependency('../../generators/javascript/text.js', ['Blockly.JavaScript.texts'], ['Blockly.JavaScript', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/javascript/text.js', ['Blockly.JavaScript.texts'], ['Blockly.JavaScript', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/javascript/variables.js', ['Blockly.JavaScript.variables'], ['Blockly.JavaScript', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/javascript/variables.js', ['Blockly.JavaScript.variables'], ['Blockly.JavaScript', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/javascript/variables_dynamic.js', ['Blockly.JavaScript.variablesDynamic'], ['Blockly.JavaScript', 'Blockly.JavaScript.variables'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/javascript/variables_dynamic.js', ['Blockly.JavaScript.variablesDynamic'], ['Blockly.JavaScript', 'Blockly.JavaScript.variables'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua.js', ['Blockly.Lua'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.utils.string'], {'lang': 'es6'}); goog.addDependency('../../generators/lua.js', ['Blockly.Lua'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/all.js', ['Blockly.Lua.all'], ['Blockly.Lua.colour', 'Blockly.Lua.lists', 'Blockly.Lua.logic', 'Blockly.Lua.loops', 'Blockly.Lua.math', 'Blockly.Lua.procedures', 'Blockly.Lua.texts', 'Blockly.Lua.variables', 'Blockly.Lua.variablesDynamic'], {'module': 'goog'}); goog.addDependency('../../generators/lua/all.js', ['Blockly.Lua.all'], ['Blockly.Lua.colour', 'Blockly.Lua.lists', 'Blockly.Lua.logic', 'Blockly.Lua.loops', 'Blockly.Lua.math', 'Blockly.Lua.procedures', 'Blockly.Lua.texts', 'Blockly.Lua.variables', 'Blockly.Lua.variablesDynamic'], {'module': 'goog'});
goog.addDependency('../../generators/lua/colour.js', ['Blockly.Lua.colour'], ['Blockly.Lua'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/lua/colour.js', ['Blockly.Lua.colour'], ['Blockly.Lua'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/lists.js', ['Blockly.Lua.lists'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/lua/lists.js', ['Blockly.Lua.lists'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
@@ -298,17 +298,17 @@ goog.addDependency('../../generators/lua/procedures.js', ['Blockly.Lua.procedure
goog.addDependency('../../generators/lua/text.js', ['Blockly.Lua.texts'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/lua/text.js', ['Blockly.Lua.texts'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/variables.js', ['Blockly.Lua.variables'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/lua/variables.js', ['Blockly.Lua.variables'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/variables_dynamic.js', ['Blockly.Lua.variablesDynamic'], ['Blockly.Lua', 'Blockly.Lua.variables'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/lua/variables_dynamic.js', ['Blockly.Lua.variablesDynamic'], ['Blockly.Lua', 'Blockly.Lua.variables'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php.js', ['Blockly.PHP'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.utils.string'], {'lang': 'es6'}); goog.addDependency('../../generators/php.js', ['Blockly.PHP'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/all.js', ['Blockly.PHP.all'], ['Blockly.PHP.colour', 'Blockly.PHP.lists', 'Blockly.PHP.logic', 'Blockly.PHP.loops', 'Blockly.PHP.math', 'Blockly.PHP.procedures', 'Blockly.PHP.texts', 'Blockly.PHP.variables', 'Blockly.PHP.variablesDynamic'], {'module': 'goog'}); goog.addDependency('../../generators/php/all.js', ['Blockly.PHP.all'], ['Blockly.PHP.colour', 'Blockly.PHP.lists', 'Blockly.PHP.logic', 'Blockly.PHP.loops', 'Blockly.PHP.math', 'Blockly.PHP.procedures', 'Blockly.PHP.texts', 'Blockly.PHP.variables', 'Blockly.PHP.variablesDynamic'], {'module': 'goog'});
goog.addDependency('../../generators/php/colour.js', ['Blockly.PHP.colour'], ['Blockly.PHP'], {'lang': 'es6'}); goog.addDependency('../../generators/php/colour.js', ['Blockly.PHP.colour'], ['Blockly.PHP'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/lists.js', ['Blockly.PHP.lists'], ['Blockly.PHP', 'Blockly.utils.string'], {'lang': 'es6'}); goog.addDependency('../../generators/php/lists.js', ['Blockly.PHP.lists'], ['Blockly.Names', 'Blockly.PHP', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/logic.js', ['Blockly.PHP.logic'], ['Blockly.PHP'], {'lang': 'es6'}); goog.addDependency('../../generators/php/logic.js', ['Blockly.PHP.logic'], ['Blockly.PHP'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/loops.js', ['Blockly.PHP.loops'], ['Blockly.PHP', 'Blockly.utils.string'], {'lang': 'es6'}); goog.addDependency('../../generators/php/loops.js', ['Blockly.PHP.loops'], ['Blockly.Names', 'Blockly.PHP', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/math.js', ['Blockly.PHP.math'], ['Blockly.PHP'], {'lang': 'es6'}); goog.addDependency('../../generators/php/math.js', ['Blockly.PHP.math'], ['Blockly.Names', 'Blockly.PHP'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/procedures.js', ['Blockly.PHP.procedures'], ['Blockly.Names', 'Blockly.PHP', 'Blockly.Variables'], {'lang': 'es6'}); goog.addDependency('../../generators/php/procedures.js', ['Blockly.PHP.procedures'], ['Blockly.Names', 'Blockly.PHP', 'Blockly.Variables'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/text.js', ['Blockly.PHP.texts'], ['Blockly.PHP'], {'lang': 'es6'}); goog.addDependency('../../generators/php/text.js', ['Blockly.PHP.texts'], ['Blockly.Names', 'Blockly.PHP'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/variables.js', ['Blockly.PHP.variables'], ['Blockly.PHP'], {'lang': 'es6'}); goog.addDependency('../../generators/php/variables.js', ['Blockly.PHP.variables'], ['Blockly.Names', 'Blockly.PHP'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php/variables_dynamic.js', ['Blockly.PHP.variablesDynamic'], ['Blockly.PHP', 'Blockly.PHP.variables']); goog.addDependency('../../generators/php/variables_dynamic.js', ['Blockly.PHP.variablesDynamic'], ['Blockly.PHP', 'Blockly.PHP.variables'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/python.js', ['Blockly.Python'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.Variables', 'Blockly.inputTypes', 'Blockly.utils.string'], {'lang': 'es6'}); goog.addDependency('../../generators/python.js', ['Blockly.Python'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.Variables', 'Blockly.inputTypes', 'Blockly.utils.string'], {'lang': 'es6'});
goog.addDependency('../../generators/python/all.js', ['Blockly.Python.all'], ['Blockly.Python.colour', 'Blockly.Python.lists', 'Blockly.Python.logic', 'Blockly.Python.loops', 'Blockly.Python.math', 'Blockly.Python.procedures', 'Blockly.Python.texts', 'Blockly.Python.variables', 'Blockly.Python.variablesDynamic'], {'module': 'goog'}); goog.addDependency('../../generators/python/all.js', ['Blockly.Python.all'], ['Blockly.Python.colour', 'Blockly.Python.lists', 'Blockly.Python.logic', 'Blockly.Python.loops', 'Blockly.Python.math', 'Blockly.Python.procedures', 'Blockly.Python.texts', 'Blockly.Python.variables', 'Blockly.Python.variablesDynamic'], {'module': 'goog'});
goog.addDependency('../../generators/python/colour.js', ['Blockly.Python.colour'], ['Blockly.Python'], {'lang': 'es6'}); goog.addDependency('../../generators/python/colour.js', ['Blockly.Python.colour'], ['Blockly.Python'], {'lang': 'es6'});